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.
Here is my take on this problem. :) I have just started learning Python, so I call this:
"The Understandable for beginners" solution.
.
.
it's answered, but it could be done with a fancy 'map/reduce' use, e.g.:
one line version: (i is an old dictionary, p is a reversed dictionary)
explanation : i.keys() and i.values() returns two lists with keys and values of the dictionary respectively. The zip function has the ability to tie together lists to produce a dictionary.
warning : This would work only if the values are hashable and unique.
I know this is old but you could quite easily find all the people in the list with your search age using list comprehension.
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.