如果指定的键包含无值,则从嵌套字典中删除项

时间:2018-05-25 22:14:13

标签: python dictionary

我有一个字典列表,如果某个键的值为None,我试图删除任何字典,它将被删除。

item_dict = [
    {'code': 'aaa0000',
     'id': 415294,
     'index_range': '10-33',
     'location': 'A010',
     'type': 'True'},
    {'code': 'bbb1458',
     'id': 415575,
     'index_range': '30-62',
     'location': None,
     'type': 'True'},
    {'code': 'ccc3013',
     'id': 415575,
     'index_range': '14-59',
     'location': 'C041',
     'type': 'True'}
    ]


for item in item_dict:
    filtered = dict((k,v) for k,v in item.iteritems() if v is not None)


# Output Results
# Item - aaa0000 is missing
# {'index_range': '14-59', 'code': 'ccc3013', 'type': 'True', 'id': 415575, 'location': 'C041'}

在我的示例中,输出结果缺少其中一个字典,如果我尝试创建新列表以附加filtered,则项目bbb1458也将包含在列表中。

我该如何纠正这个?

2 个答案:

答案 0 :(得分:3)

[item for item in item_dict if None not in item.values()]

此列表中的每个项目都是字典。如果None未出现在字典值中,则字典仅附加到此列表中。

答案 1 :(得分:1)

您可以使用列表推导创建新列表,并在所有值都不是None的条件下进行过滤:

item_dict = [
    {'code': 'aaa0000',
     'id': 415294,
     'index_range': '10-33',
     'location': 'A010',
     'type': 'True'},
    {'code': 'bbb1458',
     'id': 415575,
     'index_range': '30-62',
     'location': None,
     'type': 'True'},
    {'code': 'ccc3013',
     'id': 415575,
     'index_range': '14-59',
     'location': 'C041',
     'type': 'True'}
    ]

filtered = [d for d in item_dict if all(value is not None for value in d.values())]
print(filtered)

#[{'index_range': '10-33', 'id': 415294, 'location': 'A010', 'type': 'True', 'code': 'aaa0000'}, {'index_range': '14-59', 'id': 415575, 'location': 'C041', 'type': 'True', 'code': 'ccc3013'}]
相关问题