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.
Or in Python 3.x:
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?or better
I hope this might help...
There is none.
dict
is not intended to be used this way.If you want both the name and the age, you should be using
.items()
which gives you key(key, value)
tuples:You can unpack the tuple into two separate variables right in the
for
loop, then match the age.You should also consider reversing the dictionary if you're generally going to be looking up by age, and no two people have the same age:
so you can look up the name for an age by just doing
I've been calling it
mydict
instead oflist
becauselist
is the name of a built-in type, and you shouldn't use that name for anything else.You can even get a list of all people with a given age in one line:
or if there is only one person with each age:
which will just give you
None
if there isn't anyone with that age.Finally, if the
dict
is long and you're on Python 2, you should consider using.iteritems()
instead of.items()
as Cat Plus Plus did in his answer, since it doesn't need to make a copy of the list.