当从mongodb将数据导出到csv时,我遇到了python脚本中缺少字段名的问题。类型字段名存在于第一条记录中,但它不在其余的记录中出现。如何编写python脚本,以便在不存在类型字段的情况下给出空值。
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:"type“。请帮助我如何在脚本中添加缺失的字段名。
发布于 2016-10-25 22:23:24
当您试图获取Python字典中可能不存在的值时,可以使用字典类的字典方法。
例如,假设您有一本这样的字典:
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')
不包含type
键时,stage_record
将返回type
。
或者您可以创建默认的"UNKNOWN"
'stages.type': stage_record.get('type', "UNKNOWN"),
https://stackoverflow.com/questions/40250412
复制相似问题