-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'}
    ]


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'}

在我的示例中,输出结果缺少一个字典,如果我尝试创建一个新列表 append filtered,则 itembbb1458也将包含在列表中。

我该如何纠正这个问题?

4

2 回答 2

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

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

于 2018-05-25T22:18:51.347 回答
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'}]
于 2018-05-25T22:19:36.427 回答