检查列表字典中是否有值的最佳方法?

rag*_*ner 8 python dictionary list python-3.x

所以我有一个像这样的列表字典:

dct = {'1': ['hello','goodbye'], '2': ['not here','definitely not here']}
Run Code Online (Sandbox Code Playgroud)

什么是检查'hello'是否在我的词典中的某个列表中的最快方法

L3v*_*han 8

正如Willem Van Onsem评论的那样,实现这一目标的最简单方法是:

any('hello' in val for val in dct.values())
Run Code Online (Sandbox Code Playgroud)

any 如果给定iterable中的任何值都是真的,则返回True.

dct.values()返回一个dict_values迭代,它产生字典中的所有值.

'hello' in val for val in dct.values()是发电机表达式产生True的每个值dct'hello'是英寸

如果您想知道字符串所在的键,您可以:

keys = [key for key, value in dct.items() if 'hello' in value]
Run Code Online (Sandbox Code Playgroud)

在你的情况下,keys将是['1'].如果你仍然这样做,你可以在布尔上下文中调用use列表,例如if keys: ....