检查单词是否在列表中,该值是字典的值 [英] Check if a word is in a list that is a value of a dictionary
问题描述
我正在尝试检查单词是否在列表中,该列表是字典的值.例如,我想检查'noodles'
是否在: {1:['hello','hallo','salut','ciao','hola'],2:['eggs','noodles','bacon']}
>
我尝试过:
element ='noodles'myDict.values()中的元素
但是我得到: False
您的代码检查 element
('noodles'
)是否是字典中的值,并且不是(值是列表).
您需要检查每个列表中是否包含 element
.
如果您不关心密钥,则:
print(any(myDict.values()中value的值元素)
如果您想知道密钥(这将打印出匹配密钥的列表):
print([用于键的键,如果值中包含元素,则为myDict.items()中的值])
但是,通常来说,如果您发现自己不得不一遍又一遍地遍历字典,则可能是错误地选择了哪些键,或者完全使用了错误的数据结构.
I'm trying to check if a word is in a list that is a value of a dictionary.
For example i want to check if 'noodles'
is in:
{1:['hello', 'hallo', 'salut', 'ciao', 'hola'], 2:['eggs', 'noodles', 'bacon']}
I tried with:
element = 'noodles'
element in myDict.values()
But i get: False
Your code checks if element
('noodles'
) is a value in the dictionary, and it isn't (the values are lists).
You need to check if element
is inside every list.
If you don't care for the key:
print(any(element in value for value in myDict.values()))
If you want to know the key (this will print a list of matching keys):
print([key for key, value in myDict.items() if element in value])
But, generally speaking, if you find yourself having to loop over a dictionary over and over again, you either made a bad choice for what are the keys, or using the wrong data structure altogether.
这篇关于检查单词是否在列表中,该值是字典的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!