Best way to check a value in a dictionary of lists?
As Willem Van Onsem commented, the easiest way to achieve this is:
any('hello' in val for val in dct.values())
any
returns True if any of the values ββin the given iterable file are true.
dct.values()
returns an dict_values
iterable that gives all the values ββin the dictionary.
'hello' in val for val in dct.values()
is a generator expression that gives True
for each value dct
it is in 'hello'
.
If you want to know the keys that the string goes in, you can:
keys = [key for key, value in dct.items() if 'hello' in value]
In your case, it keys
will be ['1']
. If you do it anyway, you can just call that list in a boolean context, eg. if keys: ...
...
source to share