Get key by value in dictionary

0 votes

I wrote a function which looks 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 but how do I show the name of the person. Also, 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 backward.

How do I fix this problem?

Jul 1 in Python by ana1504.k
• 7,890 points
30 views

1 answer to this question.

0 votes

The problem here is you cannot use Dict in the above-mentioned way. You can try this:

for name, age in dictionary.items():    # for name, age in dictionary.iteritems():  (for Python 2.x)
    if age == search_age:
        print(name)
answered Jul 1 by SDeb
• 13,190 points

Related Questions In Python

0 votes
1 answer

can we sort the key value pairs in a dictionary?

we can use OrderedDict import collections result = colections.Orde ...READ MORE

answered Mar 22 in Python by Mohammad
• 3,060 points
30 views
0 votes
1 answer

Obtaining a value when given a key in python dicionaries

We cannot. Dictionaries aren't meant to be ...READ MORE

answered May 31, 2018 in Python by Nietzsche's daemon
• 4,260 points
37 views
0 votes
1 answer

Find the largest value in a dictionary

import operator stats = {'a':1000, 'b':3000, 'c': 100} max(stats.iteritems(), ...READ MORE

answered Jul 20, 2018 in Python by Nietzsche's daemon
• 4,260 points
66 views
0 votes
1 answer

How do I sort a dictionary by value?

It is not possible to sort a ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 56,940 points
30 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 346 views
0 votes
1 answer

Key error in Python

A KeyError occurs when the Key doesn't ...READ MORE

answered Sep 20, 2018 in Python by SDeb
• 13,190 points
573 views
0 votes
1 answer

Get the Current time in Python

To get the current date and time ...READ MORE

answered Oct 3, 2018 in Python by SDeb
• 13,190 points
59 views