So I have a dictionary of lists like so:
dct = {'1': ['hello','goodbye'], '2': ['not here','definitely not here']}
What's the fastest way to check if 'hello' is in one of my lists in my dictionary
To check if a value exists in a dictionary, i.e., if a dictionary has/contains a value, use the in operator and the values() method. Use not in to check if a value does not exist in a dictionary.
Using Keys() The keys() function and the "in" operator can be used to see if a key exists in a dictionary. The keys() method returns a list of keys in the dictionary, and the "if, in" statement checks whether the provided key is in the list.
Check if Variable is a Dictionary with is Operator We can use the is operator with the result of a type() call with a variable and the dict class. It will output True only if the type() points to the same memory location as the dict class. Otherwise, it will output False .
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 are truthy.
dct.values()
returns a dict_values
iterable that yields all the values in a dictionary.
'hello' in val for val in dct.values()
is a generator expression that yields True
for each value of dct
that 'hello'
is in.
If you want to know the keys the string is in, you can do:
keys = [key for key, value in dct.items() if 'hello' in value]
In your case, keys
will be ['1']
. If you do this anyways, you can then just call use that list in a boolean context, e.g. if keys: ...
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With