所以我有一个像这样的列表字典:
dct = {'1': ['hello','goodbye'], '2': ['not here','definitely not here']}
如何快速检查“hello”是否在我的字典列表中?
所以我有一个像这样的列表字典:
dct = {'1': ['hello','goodbye'], '2': ['not here','definitely not here']}
如何快速检查“hello”是否在我的字典列表中?
正如Willem Van Onsem所评论的那样,实现这一点最简单的方法是:
any('hello' in val for val in dct.values())
any
函数会在给定的可迭代对象中有任何一个元素为真时返回True。
dct.values()
函数会返回一个包含字典中所有值的可迭代对象 dict_values
。
'hello' in val for val in dct.values()
是一个生成器表达式,它会在每个字典值中是否包含字符串 'hello' 时分别返回True或False。keys = [key for key, value in dct.items() if 'hello' in value]
在您的情况下,keys
将是 ['1']
。如果您仍然这样做,那么可以在布尔上下文中直接使用该列表,例如:if keys: ...
。
any('hello' in val for val in dct.values())
。 - Willem Van Onsemdct = {'hello': 1, 'goodbye': 1, 'not here': 2, 'definitely not here': 2}
这样可以实现常数时间搜索,而不是根据字典中项数而变慢的搜索。 - Charles Duffy