Searching keys for a value in dict
suggest changeA dict has no builtin method for searching by value. You can write a function that returns the key (or keys) for a specified value:
def getKeysForValue(dictionary, value):
foundkeys = []
for key in dictionary:
if dictionary[key] == value:
foundkeys.append(key)
return foundkeys
This could also be written as an equivalent list comprehension:
def getKeysForValueComp(dictionary, value):
return [key for key in dictionary if dictionary[key] == value]
If you only care about one found key:
def getOneKeyForValue(dictionary, value):
return next(key for key in dictionary if dictionary[key] == value)
The first two functions return a list of every key that has the specified value. Since Python 3.7, dictionaries keep insertion order, so the keys come back in that order:
adict = {'a': 10, 'b': 20, 'c': 10}
getKeysForValue(adict, 10) # ['a', 'c']
getKeysForValueComp(adict, 10) # ['a', 'c']
getKeysForValueComp(adict, 20) # ['b']
getKeysForValueComp(adict, 25) # []
The other one returns only one key:
getOneKeyForValue(adict, 10) # 'a'
getOneKeyForValue(adict, 20) # 'b'
and raises a StopIteration exception if the value is not in the dict:
getOneKeyForValue(adict, 25)
StopIteration
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents