15

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

13
  • 11
    any('hello' in val for val in dct.values()). Apr 1, 2017 at 17:42
  • thanks a lot! if you submit as an answer I can accept and up vote you
    – ragardner
    Apr 1, 2017 at 17:43
  • 4
    This would be much more efficient if you inverted the data structure. dct = { 'hello': 1, 'goodbye': 1, 'not here': 2, 'definitely not here': 2 } -- that way it's a constant-time search, not one that takes longer based on how many items the dictionary has. Apr 1, 2017 at 17:47
  • @Charles: Inverting the dictionary isn't free.
    – martineau
    Apr 1, 2017 at 17:48
  • 2
    @martineau, ...moreover, even if modifying the process by which it's built isn't feasible, one can invert it once and search that inverted structure cheaply an arbitrary number of times. Apr 1, 2017 at 17:50

1 Answer 1

17

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.