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 a solution which works both in Python 2 and Python 3:
The part until
[search_age]
constructs the reverse dictionary (where values are keys and vice-versa). You could create a helper method which will cache this reversed dictionary like so:or even more generally a factory which would create a by-age name lookup method for one or more of you lists
so you would be able to do:
Note that I renamed
list
toages_by_name
since the former is a predefined type.Sometimes int() may be needed:
Here, recover_key takes dictionary and value to find in dictionary. We then loop over the keys in dictionary and make a comparison with that of value and return that particular key.
I found this answer very effective but still no very easy to read for me.
To make it more clear you can invert the key and the value of a dictionary. This is make the keys values and the values keys, as seen here.
or
which is essentially the same that this other answer.