基于键值在python中过滤嵌套字典 [英] Filter nested dictionary in python based on key values
问题描述
如何根据键值过滤python中的嵌套字典:
How do I filter a nested dictionary in python based on key values:
d = {'data': {'country': 'US', 'city': 'New York', 'state': None},
'tags': ['US', 'New York'],
'type': 'country_info',
'growth_rate': None
}
我想过滤此字典以消除NoneType值,因此得到的dict应该是:
I want to filter this dictionary to eliminate NoneType values so the resulting dict should be:
d = {'data': {'country': 'US', 'city': 'New York'},
'tags': ['US', 'New York'],
'type': 'country_info',
}
此外,dict可以有多个级别的嵌套。我想从dict中删除所有的NoneType值。
Also, the dict can have multiple levels of nesting. I want to remove all NoneType values from the dict.
推荐答案
您可以使用 dict comprehension 。
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}
递归不是过于优化Python,但是考虑到可能的嵌套数量相对较少,我不用担心。
Recursion isn't too optimised in Python, but given the relatively small number of nestings that are likely, I wouldn't worry.
在我们飞跃之前看起来不是太诡异,我认为这是一个比捕获异常更好的选择 - 大部分时间(可能我们比分支机构有更多的叶子),这个值可能不会是 dict
。
Looking before we leap isn't too Pythonic, I think it is a better option than catching the exception - as it's likely that the value will not be a dict
most of the time (it is likely we have more leaves than branches).
还要注意,在Python 2.x中,你可能想要在 iteritems()
中交换 items()
。
Also note that in Python 2.x, you probably want to swap in iteritems()
for items()
.
这篇关于基于键值在python中过滤嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!