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

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


当前回答

通过“查找”值来查找列表中的键是不容易的。但是,如果知道值,遍历键,就可以按元素在字典中查找值。如果D[element](其中D是一个字典对象)等于你要查找的键,你可以执行一些代码。

D = {'Ali': 20, 'Marina': 12, 'George':16}
age = int(input('enter age:\t'))  
for element in D.keys():
    if D[element] == age:
        print(element)

其他回答

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

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)

就是这样……

使用列表理解的一行解决方案,如果值可能出现多次,则返回多个键。

[key for key,value in mydict.items() if value == 16]

我试着阅读尽可能多的答案,以防止给出重复的答案。然而,如果你正在处理一个包含在列表中的值的字典,并且如果你想获得具有特定元素的键,你可以这样做:

d = {'Adams': [18, 29, 30],
     'Allen': [9, 27],
     'Anderson': [24, 26],
     'Bailey': [7, 30],
     'Baker': [31, 7, 10, 19],
     'Barnes': [22, 31, 10, 21],
     'Bell': [2, 24, 17, 26]}

现在让我们找到值为24的名称。

for key in d.keys():    
    if 24 in d[key]:
        print(key)

这也适用于多个值。

我发现这个答案很有效,但对我来说不太容易理解。

为了使它更清楚,您可以反转字典的键和值。这是使键值和值键,如这里所示。

mydict = {'george':16,'amber':19}
res = dict((v,k) for k,v in mydict.iteritems())
print(res[16]) # Prints george

或者Python 3,(谢谢@kkgarg)

mydict = {'george':16,'amber':19}
res = dict((v,k) for k,v in mydict.items())
print(res[16]) # Prints george

Also

print(res.get(16)) # Prints george

本质上和另一个答案是一样的。

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