我做了一个函数,它将在字典中查找年龄并显示匹配的名字:

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

我知道如何比较和查找年龄,只是不知道如何显示这个人的名字。此外,由于第5行,我得到了一个KeyError。我知道这是不正确的,但我不知道如何让它向后搜索。


当前回答

没有。Dict不是这样使用的。

dictionary = {'george': 16, 'amber': 19}
search_age = input("Provide age")
for name, age in dictionary.items():  # for name, age in dictionary.iteritems():  (for Python 2.x)
    if age == search_age:
        print(name)

其他回答

key = next((k for k in my_dict if my_dict[k] == val), None)

考虑使用Pandas。正如William McKinney的《Python for Data Analysis》中所述

另一种考虑级数的方法是固定长度的有序级数 Dict,因为它是索引值到数据值的映射。它可以是 在很多情况下,你可能会用到字典。

import pandas as pd
list = {'george':16,'amber':19}
lookup_list = pd.Series(list)

要查询您的系列,请执行以下操作:

lookup_list[lookup_list.values == 19]

收益率:

Out[1]: 
amber    19
dtype: int64

如果您需要对输出进行任何其他转换 回答成一个列表可能有用:

answer = lookup_list[lookup_list.values == 19].index
answer = pd.Index.tolist(answer)

一个简单的方法是:

list = {'george':16,'amber':19}
search_age = raw_input("Provide age")
for age in list.values():
    name = list[list==search_age].key().tolist()
    print name

这将返回值与search_age匹配的键的列表。如果需要,还可以将"list==search_age"替换为任何其他条件语句。

没有。Dict不是这样使用的。

dictionary = {'george': 16, 'amber': 19}
search_age = input("Provide age")
for name, age in dictionary.items():  # for name, age in dictionary.iteritems():  (for Python 2.x)
    if age == search_age:
        print(name)

我瞥见所有的答案,没有提到简单地使用列表理解?

这个Python的单行解决方案可以返回任意数量的给定值的所有键(在Python 3.9.1中测试):

>>> dictionary = {'george' : 16, 'amber' : 19, 'frank': 19}
>>>
>>> age = 19
>>> name = [k for k in dictionary.keys() if dictionary[k] == age]; name
['george', 'frank']
>>>
>>> age = (16, 19)
>>> name = [k for k in dictionary.keys() if dictionary[k] in age]; name
['george', 'amber', 'frank']
>>>
>>> age = (22, 25)
>>> name = [k for k in dictionary.keys() if dictionary[k] in age]; name
[]