15
d[key] = value

but how to get the keys from value?

For example:

a = {"horse": 4, "hot": 10, "hangover": 1, "hugs": 10}
b = 10

print(do_something with 10 to get ["hot", "hugs"])
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Peter
  • 315
  • 2
  • 3
  • 6
  • 1
    This is not what a map was made for, it should be the other way around. Why do you need to look for entries by their values? – JDurstberger Aug 11 '17 at 12:29

2 Answers2

38

You can write a list comprehension to pull out the matching keys.

print([k for k,v in a.items() if v == b])
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
11

Something like this can do it:

for key, value in a.iteritems():
    if value == 10:
        print key

If you want to save the associated keys to a value in a list, you edit the above example as follows:

keys = []
for key, value in a.iteritems():
    if value == 10:
        print key
        keys.append(key)

You can also do that in a list comprehension as pointed out in an other answer.

b = 10 
keys = [key for key, value in a.iteritems() if value == b]

Note that in python 3, dict.items is equivalent to dict.iteritems in python 2, check this for more details: What is the difference between dict.items() and dict.iteritems()?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Mohamed Ali JAMAOUI
  • 14,275
  • 14
  • 73
  • 117