通过字典中的值获取键值 [英] Get key by value in dictionary
本文介绍了通过字典中的值获取键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我做了一个函数,它将在字典中查找年龄并显示匹配的名称:
I made a function which will look up ages in dictionary and show the matching name:
list = {'george':16,'amber':19}
search_age = raw_input("Provide age")
for age in list.values():
if age == search_age:
name = list[age]
print name
我知道如何比较找到我的年龄只是不知道如何显示这个人的名字。另外,由于第5行,我得到一个 KeyError
。我知道这是不正确的,但我无法确定使其向后搜索。
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 to make it search backwards.
推荐答案
没有。 dict
不是以这种方式使用。
There is none. dict
is not intended to be used this way.
for name, age in list.iteritems():
if age == search_age:
print name
这篇关于通过字典中的值获取键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文