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

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


当前回答

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 )]

其他回答

如果希望根据值查找键,可以使用字典推导式创建查找字典,然后使用该字典从值中查找键。

lookup = {value: key for key, value in self.data}
lookup[value]

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

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)

就是这样……

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

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

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

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

我们可以通过以下方法得到dict的Key:

def getKey(dct,value):
     return [key for key in dct if (dct[key] == value)]

你可以通过使用dict.keys(), dict.values()和list.index()方法来获取key,参见下面的代码示例:

names_dict = {'george':16,'amber':19}
search_age = int(raw_input("Provide age"))
key = names_dict.keys()[names_dict.values().index(search_age)]