Get key by value in dictionary
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: How can I get list of values from dict?
There is none. dict
is not intended to be used this way.
dictionary = {'george': 16, 'amber': 19}search_age = input("Provide age")for name, age in dictionary.items(): # for name, age in dictionary.iteritems(): (for Python 2.x) if age == search_age: print(name)
If you want both the name and the age, you should be using .items()
which gives you key (key, value)
tuples:
for name, age in mydict.items(): if age == search_age: print name
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:
{16: 'george', 19: 'amber'}
so you can look up the name for an age by just doing
mydict[search_age]
I've been calling it mydict
instead of list
because list
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:
[name for name, age in mydict.items() if age == search_age]
or if there is only one person with each age:
next((name for name, age in mydict.items() if age == search_age), None)
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.