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

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。我知道这是不正确的,但我不知道如何让它向后搜索。


当前回答

my_dict = {'A': 19, 'B': 28, 'carson': 28}
search_age = 28

只拿一个

name = next((name for name, age in my_dict.items() if age == search_age), None)
print(name)  # 'B'

获取多个数据

name_list = [name for name, age in filter(lambda item: item[1] == search_age, my_dict.items())]
print(name_list)  # ['B', 'carson']

其他回答

以下是我的看法。这对于显示多个结果很有好处,以防您需要一个结果。所以我也添加了这个列表

myList = {'george':16,'amber':19, 'rachel':19, 
           'david':15 }                         #Setting the dictionary
result=[]                                       #Making ready of the result list
search_age = int(input('Enter age '))

for keywords in myList.keys():
    if myList[keywords] ==search_age:
    result.append(keywords)                    #This part, we are making list of results

for res in result:                             #We are now printing the results
    print(res)

就是这样……

dictionary = {'george' : 16, 'amber' : 19}
search_age = raw_input("Provide age")
key = [filter( lambda x: dictionary[x] == k  , dictionary ),[None]][0] 
# key = None from [None] which is a safeguard for not found.

多次使用:

keys = [filter( lambda x: dictionary[x] == k  , dictionary )]

它被回答了,但它可以用一个奇特的“映射/减少”使用来完成,例如:

def find_key(value, dictionary):
    return reduce(lambda x, y: x if x is not None else y,
                  map(lambda x: x[0] if x[1] == value else None, 
                      dictionary.iteritems()))
a = {'a':1,'b':2,'c':3}
{v:k for k, v in a.items()}[1]

或更好的

{k:v for k, v in a.items() if v == 1}

我也在寻找同样的问题,最后得到了我的变体: Found_key = [a[0] for a in dict.items() if a[1] == 'value'][0]

仅适用于键具有唯一值的情况(这就是我的情况)。