如何从列表字典的值中获取所有键? [英] How to get all keys from a value for a dict of lists?
本文介绍了如何从列表字典的值中获取所有键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样格式的字典
d = {
"Fruit_1" : ["mango", "apple"],
"Fruit_2" : ["apple"],
"Fruit_3" : ["mango", "banana", "apple", "kiwi", "orange"]
}
我传递的值是"mango",我想获得所有仅芒果出现的对应键.我无法在出现值的任何地方获取相应的键.
I'm passing a value as "mango" and I want to get all corresponding keys where only mango occurs. I am not able to get corresponding keys where ever value occurs.
推荐答案
您也许可以这样做:
d = {
"Fruit_1" : ["mango", "apple"],
"Fruit_2" : ["apple"],
"Fruit_3" : ["mango", "banana", "apple", "kiwi", "orange"]
}
# list comprehension
mango_keys = [fruit for fruit in d.keys() if "mango" in d[fruit]]
print(mango_keys)
# ['Fruit_1', 'Fruit_3']
# or more traditional for-loop (but non pythonic)
for fruit in d.keys():
if "mango" in d[fruit]:
print(fruit)
这篇关于如何从列表字典的值中获取所有键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文