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

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


当前回答

如果你想要名字和年龄,你应该使用.items(),它会给你key (key, value)元组:

for name, age in mydict.items():
    if age == search_age:
        print name

您可以在for循环中将元组解包为两个单独的变量,然后匹配年龄。

如果你通常要根据年龄查找,而且没有两个人的年龄相同,你还应该考虑颠倒字典:

{16: 'george', 19: 'amber'}

所以你可以通过这样做来查找这个名字

mydict[search_age]

我一直称它为mydict而不是list,因为list是内置类型的名称,你不应该将这个名称用于其他任何类型。

你甚至可以在一行中得到给定年龄的所有人的列表:

[name for name, age in mydict.items() if age == search_age]

或者如果每个年龄只有一个人:

next((name for name, age in mydict.items() if age == search_age), None)

如果没有这个年龄的人,就会给你None。

最后,如果字典很长并且你使用的是Python 2,你应该考虑使用.iteritems()而不是像Cat Plus Plus在他的回答中所做的那样使用.items(),因为它不需要复制列表。

其他回答

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

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()))
key = next((k for k in my_dict if my_dict[k] == val), None)

你可以通过使用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)]
get_key = lambda v, d: next(k for k in d if d[k] is v)
for name in mydict:
    if mydict[name] == search_age:
        print(name) 
        #or do something else with it. 
        #if in a function append to a temporary list, 
        #then after the loop return the list