2016-10-25 64 views
1

我在從mongodb將數據導出到csv時,遇到python腳本中缺少字段名稱的問題。類型字段名稱存在於第一條記錄中,但它不會出現在其餘記錄中。如果編寫python腳本,如果它不存在,則爲類型字段提供空值。從mongodb導出json數據到csv

的MongoDB集合的樣本:

"stages": [ 
    { 
     "interview": false, 
     "hmNotification": false, 
     "hmStage": false, 
     "type": "new", 
     "isEditable": false, 
     "order": 0, 
     "name": { 
      "en": "New" 
     }, 
     "stageId": "51d1a2f4c0d9887b214f3694" 
    }, 
    { 
     "interview": false, 
     "hmNotification": true, 
     "isEditable": true, 
     "order": 1, 
     "hmStage": true, 
     "name": { 
      "en": "Pre-Screen" 
     }, 
     "stageId": "51f0078d7297363f62059699" 
    }, 
    { 
     "interview": false, 
     "hmNotification": false, 
     "hmStage": false, 
     "isEditable": true, 
     "order": 2, 
     "name": { 
      "en": "Phone Screen" 
     }, 
     "stageId": "51d1a326c0d9887721778eae" 
    }] 

Python腳本的示例:

import csv 
cursor = db.workflows.find({}, {'_id': 1, 'stages.interview': 1, 'stages.hmNotification': 1, 'stages.hmStage': 1, 'stages.type':1, 'stages.isEditable':1, 'stages.order':1, 
'stages.name':1, 'stages.stageId':1 }) 
flattened_records = [] 
for stages_record in cursor: 
    stages_record_id = stages_record['_id'] 
    for stage_record in stages_record['stages']: 
     flattened_record = { 
      '_id': stages_record_id, 
      'stages.interview': stage_record['interview'], 
      'stages.hmNotification': stage_record['hmNotification'], 
      'stages.hmStage': stage_record['hmStage'], 
      'stages.type': stage_record['type'], 
      'stages.isEditable': stage_record['isEditable'], 
      'stages.order': stage_record['order'], 
      'stages.name': stage_record['name'], 
      'stages.stageId': stage_record['stageId']}     
     flattened_records.append(flattened_record) 

運行python腳本時,它顯示KeyError異常: 「類型」。請幫助我如何在腳本中添加缺少的字段名稱。

回答

0

當您嘗試提取可能不存在於Python字典中的值時,可以使用dict類的.get()方法。

舉例來說,假設你有一個這樣的詞典:

my_dict = {'a': 1, 
      'b': 2, 
      'c': 3} 

可以使用get方法來獲取生存的關鍵之一:

>>> print(my_dict.get('a')) 
1 

但是,如果你嘗試得到一個不存在的密鑰(如does_not_exist),默認情況下您將得到None

>>> print(my_dict.get("does_not_exist")) 
None 

如文檔中提到的,你也可以提供,當該鍵不存在,將返回一個默認值:

>>> print(my_dict.get("does_not_exist", "default_value")) 
default_value 

但如果鍵確實存在此默認值將不會被使用在字典(如果該鍵不存在,你會得到它的值):

>>> print(my_dict.get("a", "default_value")) 
1 

知道,當你建立你的flattened_record你可以這樣做:

'stages.hmStage': stage_record['hmStage'], 
'stages.type': stage_record.get('type', ""), 
'stages.isEditable': stage_record['isEditable'], 

因此,如果stage_record字典不包含密鑰type,get('type')將返回一個空字符串。

您也可以嘗試只用:

'stages.hmStage': stage_record['hmStage'], 
'stages.type': stage_record.get('type'), 
'stages.isEditable': stage_record['isEditable'], 

然後stage_record.get('type')將返回Nonestage_record不包含type關鍵。

或者你可以使默認"UNKNOWN"

'stages.type': stage_record.get('type', "UNKNOWN"), 
+1

它工作時,增加了「stages.typ非常好‘:stage_record.get。在python腳本(’類型」)類型的值出現在CSV文件。非常感謝。 – user7070824

+0

感謝您的幫助。如何刪除u字母,括號和Python中子字段的名稱?謝謝。 – user7070824