基于键值筛选python中的嵌套字典
如何基于键值筛选python中的嵌套字典:基于键值筛选python中的嵌套字典,python,dictionary,Python,Dictionary,如何基于键值筛选python中的嵌套字典: d = {'data': {'country': 'US', 'city': 'New York', 'state': None}, 'tags': ['US', 'New York'], 'type': 'country_info', 'growth_rate': None } 我想筛选此字典以消除非类型值,因此生成的dict应为: d = {'data': {'country': 'US', 'city':
d = {'data': {'country': 'US', 'city': 'New York', 'state': None},
'tags': ['US', 'New York'],
'type': 'country_info',
'growth_rate': None
}
我想筛选此字典以消除非类型值,因此生成的dict应为:
d = {'data': {'country': 'US', 'city': 'New York'},
'tags': ['US', 'New York'],
'type': 'country_info',
}
此外,dict可以有多个嵌套级别。我想从dict中删除所有非类型的值。您可以使用 递归在Python中并没有得到太多的优化,但考虑到可能出现的嵌套数量相对较少,我不会担心 在我们跳跃之前看一看并不是太像python,我认为这是一个比捕获异常更好的选择——因为在大多数情况下,值可能不是一个
dict
(很可能我们的叶子比分支多)
还要注意的是,在Python2.x中,您可能希望在
iteritems()
中交换items()
我非常感谢@Lattyware给出的答案。它帮助我过滤出嵌套对象并删除空值,而不管类型是dict
、list
还是str
以下是我的想法:
remove-keys-with-empty-values.py
执行
我喜欢你的答案,这可能有点吹毛求疵,但如果value不是None,它会读得更好。@BrianHicks注意到并修复了,非常正确。我想如果我们想更像pythonic,你应该使用
if hasattr(item,'items')
,或者假设它被传递给了一本字典。您可以按原样将[1,2,None]
传递给函数,并用nones返回相同的项。@BrianHicks我不认为其目的是从列表中删除None
——我认为这纯粹是删除值为None
的键hasattr(item,'items')
可能也有点好,这是真的。@Lattyware:为什么“dict comprehension”链接会链接到关于列表理解的YouTube视频?因为它够近了?
def remove_keys_with_none_values(item):
if not hasattr(item, 'items'):
return item
else:
return {key: remove_keys_with_none_values(value) for key, value in item.items() if value is not None}
# remove-keys-with-empty-values.py
from pprint import pprint
def remove_keys_with_empty_values(item):
if hasattr(item, 'items'):
return {key: remove_keys_with_empty_values(value) for key, value in item.items() if value==0 or value}
elif isinstance(item, list):
return [remove_keys_with_empty_values(value) for value in item if value==0 or value]
else:
return item
d = {
'string': 'value',
'integer': 10,
'float': 0.5,
'zero': 0,
'empty_list': [],
'empty_dict': {},
'empty_string': '',
'none': None,
}
d['nested_dict'] = d.copy()
l = d.values()
d['nested_list'] = l
pprint({
"DICT FILTERED": remove_keys_with_empty_values(d),
"DICT ORIGINAL": d,
"LIST FILTERED": remove_keys_with_empty_values(l),
"LIST ORIGINAL": l,
})
python remove-keys-with-empty-values.py
{'DICT FILTERED': {'float': 0.5,
'integer': 10,
'nested_dict': {'float': 0.5,
'integer': 10,
'string': 'value',
'zero': 0},
'nested_list': [0,
'value',
10,
0.5,
{'float': 0.5,
'integer': 10,
'string': 'value',
'zero': 0}],
'string': 'value',
'zero': 0},
'DICT ORIGINAL': {'empty_dict': {},
'empty_list': [],
'empty_string': '',
'float': 0.5,
'integer': 10,
'nested_dict': {'empty_dict': {},
'empty_list': [],
'empty_string': '',
'float': 0.5,
'integer': 10,
'none': None,
'string': 'value',
'zero': 0},
'nested_list': [{},
0,
'value',
None,
[],
10,
0.5,
'',
{'empty_dict': {},
'empty_list': [],
'empty_string': '',
'float': 0.5,
'integer': 10,
'none': None,
'string': 'value',
'zero': 0}],
'none': None,
'string': 'value',
'zero': 0},
'LIST FILTERED': [0,
'value',
10,
0.5,
{'float': 0.5,
'integer': 10,
'string': 'value',
'zero': 0}],
'LIST ORIGINAL': [{},
0,
'value',
None,
[],
10,
0.5,
'',
{'empty_dict': {},
'empty_list': [],
'empty_string': '',
'float': 0.5,
'integer': 10,
'none': None,
'string': 'value',
'zero': 0}]}