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?
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?
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'
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
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.
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)
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])]