Python 如果指定的键不包含任何值,请从嵌套字典中删除项
我有一个字典列表,在其中我试图删除任何字典。如果某个键的值为None,它将被删除Python 如果指定的键不包含任何值,请从嵌套字典中删除项,python,dictionary,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',
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'}
在我的示例中,输出结果缺少一个字典,如果我试图创建一个新列表以附加筛选的
,则列表中也将包含项bbb1458
我怎样才能纠正这个问题
[item for item in item_dict if None not in item.values()]
此列表中的每一项都是一本词典。只有当
None
未出现在字典值中时,字典才会附加到此列表 您可以使用列表理解创建一个新列表,在所有值都不是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'}]
您经常(每次迭代)覆盖筛选的内容。您的问题是“如果某个键为无”,您希望删除内容,但您的示例代码会删除任何值为无的内容,而不仅仅是某个键的值。您想要哪一个?您的问题还说,如果某个键的值为None,您希望删除整个字典,但您的示例代码将返回已删除该键-值对的字典副本。再说一遍,你想要哪一个?@abarnert请原谅我没有被指定,我已经编辑了标题。如果发现指定的键值为非,我想删除字典。感谢您返回。假设在这种情况下,如果item
aaa0000
keyindex\u range
也是None
,您的解决方案不会也删除aaa0000字典吗?我是否可以缩小范围,以便它将检查指定的键,在本例中为位置
?是[项中的项对项_dict如果项[location]!=None]
,则假定您的词典都有此特殊的位置
键。如果某些词典没有此键,则会出现KeyError
。如果有效的dict可以排除该键,则可以使用has_key(…)和跳过KeyError
。@TemporalWolf注意有_key(…)
已从Python3中删除,如果您试图在Python3中使用它,将抛出一个AttributeError
。在Python3中,如果项中的'location'和项['location']!=None],则必须是,
,以便在键'location'未出现时保留字典。如果指定的键没有出现,则不清楚所需的行为是什么。谢谢大家,这就是我要寻找的。