Best way to check a value in a dictionary of lists?

So, I have a dictionary of lists like this:

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

+3


source to share


1 answer


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

...

+2


source







All Articles