在字典中按值获取键

在字典中按值获取键

我做了一个函数,可以在Dictionary并显示匹配的名称:

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

我知道如何比较和找出年龄,只是不知道如何显示这个人的名字。另外,我还得到了一个KeyError因为第5行。我知道这是不正确的,但我不知道如何使它向后搜索。


慕姐8265434
浏览 2132回答 3
3回答

米琪卡哇伊

根本就没有。dict不打算以这种方式使用。for name, age in dictionary.items():    # for name, age in dictionary.iteritems():  (for Python 2.x)     if age == search_age:         print(name)

ITMISS

mydict = {'george':16,'amber':19}print mydict.keys()[mydict.values().index(16)] # Prints george或者在Python3.x中:mydict = {'george':16,'amber':19}print(list(mydict.keys())[list(mydict.values()).index(16)]) # Prints george基本上,它将字典的值分隔到一个列表中,查找您所拥有的值的位置,并在该位置获取键。更多关于keys()和.values()在Python 3中:Python:从dict获取值列表的最简单方法?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python