在字典python中访问列表中的项目 [英] Accessing items in lists within dictionary python
问题描述
我有一本字典,该字典具有与列表关联的键.
I have a dictionary that has keys associated with lists.
mydict = {'fruits': ['banana', 'apple', 'orange'],
'vegetables': ['pepper', 'carrot'],
'cheese': ['swiss', 'cheddar', 'brie']}
我想做的是使用一个if语句,如果我在字典中的任何列表中搜索item及其项,它将返回键.这就是我正在尝试的:
What I want to do is use an if statement that if I search for item and its in any of the lists within the dictionary it will return the key. This is what I was trying:
item = cheddar
if item in mydict.values():
print key
但是它什么也没做,输出应该是:
but it doesn't do anything, the output should be:
cheese
这似乎很简单,但是我无法弄清楚.任何帮助都很棒.
This seems like a simple thing but I just can't figure it out. Any help is awesome.
推荐答案
您必须使用for
,简单的if
不足以检查一组未知的列表:
You'll have to use a for
, a simple if
is not enough to check an unknown set of lists:
for key in mydict.keys():
if item in mydict[key]:
print key
没有显式for
语句的方法可能是这样的:
An approach without an explicit for
statement would be possible like this:
foundItems = (key for key, vals in mydict.items() if item in vals)
返回与item
关联的所有键.但是在内部,仍然存在某种迭代.
which returns all keys which are associated with item
. But internally, there's still some kind of iteration going on.
这篇关于在字典python中访问列表中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!