我正在尝试从嵌套字典中获取键和值:
举个例子:
a = {'one': {'animal': 'chicken'},
'two': {'fish': {'sea':'shark'}}}
是否有任何pythonic方法从嵌套字典中获取值?喜欢直接看到'鱼'的价值?
提前致谢
答案 0 :(得分:0)
如果你想找到所有带有" fish"在嵌套字典中输入密钥,您可以修改此答案flatten nested python dictionaries-compressing keys - answer @Imran
import collections
def get_by_key_in_nested_dict(d, key, parent_key='', sep='_'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if key==k:
items.append((new_key, v))
if isinstance(v, collections.MutableMapping):
items.extend(get_by_key_in_nested_dict(v, key, new_key, sep).items())
return dict(items)
用,
test = {
'one': {
'animal': 'chicken'
},
'two': {
'fish': {
'sea':'shark',
'fish':0
}
},
'fish':[1,2,3]
}
get_by_key_in_nested_dict(test,"fish")
您将获得所有具有密钥" fish"
的项目{
'fish': [1, 2, 3],
'two_fish': {'fish': 0, 'sea': 'shark'},
'two_fish_fish': 0
}