0

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'

Dong-gyun Kim
  • 411
  • 5
  • 23
  • I tried your code with python 2.7, got `['key2']` so it definitely seems to work. In python 3 you need to change `.iteritems()` to just `.items()`. Tried that too, same answer - your code works. – Faboor May 05 '19 at 22:38

2 Answers2

1

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
AzMoo
  • 486
  • 3
  • 10
1

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'
jferard
  • 7,835
  • 2
  • 22
  • 35