Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 794
user998316 Avatar asked Nov 05 '11 21:11

user998316


People also ask

Can you get the key of a dictionary by value Python?

A Python dictionary is a collection of key-value pairs, where each key has an associated value. Use square brackets or get() method to access a value by its key. Use the del statement to remove a key-value pair by the key from the dictionary. Use for loop to iterate over keys, values, key-value pairs in a dictionary.

How do I find a specific key in a dictionary?

Method 1 : Using List. Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list.

How do you search a dictionary for a value?

By using the dict. get() function, we can easily get the value by given key from the dictionary. This method will check the condition if the key is not found then it will return none value and if it is given then it specified the value.

How do you get a specific value from a dictionary in Python?

In Python, you can get the value from a dictionary by specifying the key like dict[key] . In this case, KeyError is raised if the key does not exist. Note that it is no problem to specify a non-existent key if you want to add a new element.


1 Answers

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?

like image 188
Stênio Elson Avatar answered Sep 19 '22 13:09

Stênio Elson