1

Dictionary values are lists:

dictionary_1 = {"ABC": [1,2,3], "DEF":[4,5,6]}

How do I get key of 5, which is "DEF" from dictionary_1 in python?

alwbtc
  • 28,057
  • 62
  • 134
  • 188

5 Answers5

2

You can create reverse dict:

>>> d = {i:k for k,v in dictionary_1.items() for i in v}
>>> d
{1: 'ABC', 2: 'ABC', 3: 'ABC', 4: 'DEF', 5: 'DEF', 6: 'DEF'}
>>> d[5]
'DEF'
ndpu
  • 22,225
  • 6
  • 54
  • 69
1

Maybe like this?

my_value = 5
for k, v in dictionary_1.iteritems():
    if my_value in v:
        print k
        break
else:
    print "No key, defaulting to GHJ"

Demo:

    In [12]: my_value = 8

    In [13]: for k, v in dictionary_1.iteritems():
        if my_value in v:
            print "Key for %s is %s" % (my_value, k)
            break
    else:
        print "No key found for %s, defaulting to GHJ" % my_value

    No key found for 8, defaulting to GHJ
msvalkon
  • 11,887
  • 2
  • 42
  • 38
  • If item is not found in dictionary, then it should return a default value, like "GHJ". How would you do it above? – alwbtc Feb 18 '14 at 08:47
  • @alwbtc updated my answer. It's for/else pattern, if the key is not found, the code will never `break` and the `else` clause is executed. – msvalkon Feb 18 '14 at 08:54
1

You'll have to search through the dictionary for that:

try:
    key = next(k for k, v in dictionary_1.iteritems() if 5 in v)
except StopIteration:
    raise KeyError('Key for 5 not found')

This assumes you are looking for a key. To find all keys you can use a list comprehension:

keys = [k for k, v in dictionary_1.iteritems() if 5 in v]

where the list could be empty.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Haven't seen using `next` in this way..thanks. – rajpy Feb 19 '14 at 03:19
  • @alwbtc: If you want default value, use this `key = next((k for k, v in d.iteritems() if 9 in v), 'GHJ')` and remove try..except. – rajpy Feb 19 '14 at 03:22
0

One way to do it is:

dictionary_1 = {"ABC": [1,2,3], "DEF":[4,5,6]}
for k, v in dictionary_1.items():
    if 5 in v:
        print(k)
Douglas Denhartog
  • 2,036
  • 1
  • 16
  • 23
0

Assuming you can check if 5 is in [4,5,6] list, you can also try:

dictionary_1 = {"ABC": [1,2,3], "DEF":[4,5,6]}

print dictionary_1.keys()[dictionary_1.values().index([4,5,6])] 
tamiros
  • 339
  • 1
  • 4
  • 10