0 votes
1 view
in Python by (47.8k points)

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 backward.

1 Answer

0 votes
by (107k points)

You can use the below-mentioned code in Python 2.x this will print george which is the key in our dictionary:-

mydict = {'george':16,'amber':19}

print mydict.keys()[mydict.values().index(16)]

If you are using Python 3.x you need to do as follows:

mydict = {'george':16,'amber':19} print(list(mydict.keys())[list(mydict.values()).index(16)])

Basically what it does is, it separates the dictionary's values in a list, finds the position of the value you have, and gets the key at that position.

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
asked Jul 2, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
asked Aug 23, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...