jramm
jramm

Reputation: 6655

How can I find the key in a dict whose matching value, which is a list, contains X?

I have a python dictionary which maps a number of words to lists of other words. E.g:

d = {"Hello": ["hi", "hello", "hey", "yo"],
     "Goodbye": ["bye", "see ya", "goodbye", "laters"]}

Given a lowercase word, I want to check whether that word is in any of the dictionary values and retrieve the corresponding key.

I'm sure there is some elegant solution using some of pythons' functional capabilities (itertools perhaps) but its just beyond my reach...

Any ideas?

Upvotes: 1

Views: 60

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

You can have multiple keys matching, so you'd need to produce a set (since order doesn't matter and keys are unique):

{key for key, words in d.iteritems() if search_word in words}

If you are only interested in the first match (because you keep your words unique, say), you can use next() and a generator expression:

next((key for key, words in d.iteritems() if search_word in words), None)

You probably want to create an inverse index if you need to test for multiple words:

reverse_index = {}
for key, words in d.iteritems():
    for word in words:
        reverse_index.setdefault(word, set()).add(key)

after which you can just use:

reverse_index.get(search_word, set())

to get the same result.

For unique words in your lists, the reverse index would simply be:

reverse_index = {word: key for key, words in d.iteritems() for word in words}
reverse_index.get(search_word)

Upvotes: 4

Related Questions