A reverse dictionary lookup will return a list containing all the keys in a dictionary. Dictionary keys map values and are used to access values in dictionaries. Here is the same functionality but written with list comprehension so it fits on one line.
Use items() to Reverse a Dictionary in Python Reverse the key-value pairs by looping the result of items() and switching the key and the value. The k and v in the for loop stands for key and value respectively.
If you want to find the key by the value, you can use a dictionary comprehension to create a lookup dictionary and then use that to find the key from the value.
Use the list[index] function to get index numbers from the dictionary. It will return the key and also use the items() function to return a collection from a dictionary.
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
.
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())
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With