蟒蛇:找到所有键与一个值 [英] python: find all keys with a value
本文介绍了蟒蛇:找到所有键与一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有如下字典:
mydict = {'a' : 'apple',
'b' : 'bobb',
'c' : {
'd' : 'dog'
},
'e' : 'dog'
}
假设我要查找所有值为'dog
'的键,如果嵌套,则键之间应用点分隔.
Suppose I want to find all the keys with value 'dog
'In case of nesting, the keys should be separated by a dot.
所以输出应该是列表['e', 'c.d']
现在,如果我在python 3中编写以下代码,它将仅输出'e
'.
Now if I write below code in python 3, it only outputs 'e
'.
print(list(mydict.keys())[list(mydict.values()).index('dog')])
如何获取嵌套键?
推荐答案
您可以使用如下所示的递归函数:
You can use a recursion function like following:
def find_key(mydict, pre=tuple()):
for key, value in mydict.items():
if isinstance(value, dict):
yield from find_key(value, pre=pre+(key,))
elif value == 'dog':
if pre:
yield '.'.join(pre + (key,))
else:
yield key
测试:
In [23]: list(find_key(mydict))
Out[23]: ['e', 'c.d']
In [26]: mydict = {'a' : 'apple',
'b' : 'bobb',
'c' : {
'd' : 'dog'
},
'e' : 'dog',
'k':{'f':{'c':{'x':'dog'}}}}
In [27]:
In [27]: list(find_key(mydict))
Out[27]: ['k.f.c.x', 'e', 'c.d']
这篇关于蟒蛇:找到所有键与一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文