Inverse dictionary lookup in Python
Is there any straightforward way of finding a key by knowing the value within a dictionary?
All I can think of is this:
key = [key for key, value in dict_obj.items() if value == 'value'][0]
Solution 1:
Your list comprehension goes through all the dict's items finding all the matches, then just returns the first key. This generator expression will only iterate as far as necessary to return the first value:
key = next(key for key, value in dd.items() if value == 'value')
where dd
is the dict. Will raise StopIteration
if no match is found, so you might want to catch that and return a more appropriate exception like ValueError
or KeyError
.
Solution 2:
There are cases where a dictionary is a one:one mapping
Eg,
d = {1: "one", 2: "two" ...}
Your approach is ok if you are only doing a single lookup. However if you need to do more than one lookup it will be more efficient to create an inverse dictionary
ivd = {v: k for k, v in d.items()}
If there is a possibility of multiple keys with the same value, you will need to specify the desired behaviour in this case.
If your Python is 2.6 or older, you can use
ivd = dict((v, k) for k, v in d.items())
Solution 3:
This version is 26% shorter than yours but functions identically, even for redundant/ambiguous values (returns the first match, as yours does). However, it is probably twice as slow as yours, because it creates a list from the dict twice.
key = dict_obj.keys()[dict_obj.values().index(value)]
Or if you prefer brevity over readability you can save one more character with
key = list(dict_obj)[dict_obj.values().index(value)]
And if you prefer efficiency, @PaulMcGuire's approach is better. If there are lots of keys that share the same value it's more efficient not to instantiate that list of keys with a list comprehension and instead use use a generator:
key = (key for key, value in dict_obj.items() if value == 'value').next()
Solution 4:
Since this is still very relevant, the first Google hit and I just spend some time figuring this out, I'll post my (working in Python 3) solution:
testdict = {'one' : '1',
'two' : '2',
'three' : '3',
'four' : '4'
}
value = '2'
[key for key in testdict.items() if key[1] == value][0][0]
Out[1]: 'two'
It will give you the first value that matches.