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

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= {'george':16,'amber':19}

dict((v,k) for k,v in d.items()).get(16)

回显如下:

-> prints george

其他回答

通过“查找”值来查找列表中的键是不容易的。但是,如果知道值,遍历键,就可以按元素在字典中查找值。如果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)
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}
key = next((k for k in my_dict if my_dict[k] == val), None)

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

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)

这也适用于多个值。

没有。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)