Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if value in dictionary of lists?

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

like image 893
ragardner Avatar asked Apr 01 '17 17:04

ragardner


People also ask

How do you check if a value is in a 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.

How do you check if a value is present in a list of dictionary Python?

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.

How do you check if a variable is in a dictionary Python?

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 .


1 Answers

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: ....

like image 68
L3viathan Avatar answered Nov 07 '22 10:11

L3viathan