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, 2019 in Python by ana1504.k
• 7,910 points
1,012 views

2 answers 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, 2019 by SDeb
• 13,300 points
0 votes

I have slightly modified your program to get the output as per age. Here is the code

dictionary = {'george' : 16, 'amber' : 19}
search_age = int(input("Provide age"))

for key, value in dictionary.items():
    if value == search_age:
        print(key, '::', value)
answered Nov 25, 2021 by Python Coder

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.Ord ...READ MORE

answered Mar 22, 2019 in Python by Mohammad
• 3,230 points
583 views
0 votes
3 answers

How can I sort a dictionary by key in python?

Another way could be: color_dict = {'red':'#FF0000',           'green':'#008000',           'black':'#000000',           'white':'#FFFFFF'} for ...READ MORE

answered Dec 28, 2020 in Python by Thomas Walenta
1,126 views
0 votes
2 answers

Obtaining a value when given a key in python dicionaries

Yes you can check below code dictionary = ...READ MORE

answered Nov 25, 2021 in Python by Suhas
847 views
0 votes
2 answers

Find the largest value in a dictionary

Use below running code which is simple ...READ MORE

answered Nov 25, 2021 in Python by Suhas
1,245 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,464 views
0 votes
1 answer
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,300 points
1,488 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,300 points
681 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP