Get key by value in dictionary


I made a function which will look up ages in a Dictionary and show the matching name:

dictionary = {'george' : 16, 'amber' : 19}
search_age = raw_input("Provide age")
for age in dictionary.values():
    if age == search_age:
        name = dictionary[age]
        print name

I know how to compare and find the age I just don't know how to show the name of the person. Additionally, I am getting a KeyError because of line 5. I know it's not correct but I can't figure out how to make it search backwards.

4/1/2018 2:44:54 PM

Accepted Answer

There is none. dict is not intended to be used this way.

for name, age in dictionary.items():    # for name, age in dictionary.iteritems():  (for Python 2.x)
    if age == search_age:
9/9/2018 1:22:17 PM

mydict = {'george':16,'amber':19}
print mydict.keys()[mydict.values().index(16)] # Prints george

Or in Python 3.x:

mydict = {'george':16,'amber':19}
print(list(mydict.keys())[list(mydict.values()).index(16)]) # Prints george

Basically, it separates the dictionary's values in a list, finds the position of the value you have, and gets the key at that position.

More about keys() and .values() in Python 3: Python: simplest way to get list of values from dict?

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow