Can I get the key of a given value (in a dictionary)?

Talking about Python dictionaries…
I mean, I know I can get the value associated to a key, but I was wondering, is there a way to get the key associated to a given value?

2 Likes

You could do:

for key,value in awesomeDict.items():
   if value == theValueAssociatedToTheKeyIwant:
      # do stuff with that key in the loop
6 Likes

Aye, as per @irlfede’s comment there’s no in-built way to do it. It’s worth noting that several keys could share the same value (==) or even the same object (is). If you know what’s in your dictionary and you’re sure there’s no chance of repeats then you can get away with it but make sure that’s always the case or you may need to think about returning multiple keys.

5 Likes

You could invert the dictionary, as follows:

def invert_dictionary(d):
  inv = {}
  for key, val in d.items():
    if val in inv:
      inv[val].append(key)
    else:
      inv[val] = [key]
  return inv

d = {"apple": 2, "orange": 2, "pear":1, "cherry":4, "banana": 1}
inverted_dict = invert_dictionary(d)
print(inverted_dict)
print(inverted_dict[1])

Output:

{2: ['apple', 'orange'], 1: ['pear', 'banana'], 4: ['cherry']}
['pear', 'banana']
4 Likes

Thanks a bunch, everyone. Those were really helpful :blush:
I found it weird that there was no built-in way to do it, but thanks to @tgrtim I think I get why now.

1 Like