Search code examples
pythondictionaryiteritems

How to get a key among the several values?


I would like to find the key from one value. But, a key has several values.

I can't find the key by using the typical way to find the key from the value.

I already tried dict.items() and dict.iterms() instead of dict.iteritems()

But doesn't work.

dict = {'key1': ["value1",  "value2"],
       'key2': ["value3", "value4"] }

l = list()
for k, v in dict.iteritems():
    if 'value3' in v:
        l.append(k)
print(l)

I like to get the key from one value. For example, if I put 'value3' then print 'key2'


Solution

  • Avoid the keyword dict to name your dictionary.

    You can reverse the dict key -> values to a dict value -> key:

    >>> d = {'key1': ["value1",  "value2"], 'key2': ["value3", "value4"] }
    >>> e = {v: k for k, vs in d.items() for v in vs}
    >>> e
    {'value1': 'key1', 'value2': 'key1', 'value3': 'key2', 'value4': 'key2'}
    >>> e['value3']
    'key2'