How to get a key among the several values?

63 Views Asked by At

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'

2

There are 2 best solutions below

0
jferard On BEST ANSWER

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'
0
AzMoo On

dict.items() definitely should work.

>>> foo = {'a': 'A', 'b': 'B'}
>>> foo.items()
dict_items([('a', 'A'), ('b', 'B')])
>>> for k, v in foo.items():
...   print(k, v)
...
a A
b B