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

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


当前回答

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}

其他回答

你可以通过使用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)]

试试下面的一行代码来反转字典:

reversed_dictionary = dict(map(reversed, dictionary.items()))

我意识到已经有很长一段时间了,最初的提问者可能不再需要答案,但如果您实际上可以控制这段代码,那么这些答案都不是好的答案。您只是使用了错误的数据结构。这是双向字典用例的完美说明:

>>> from collections import defaultdict, UserDict
>>> class TwoWayDict(UserDict):
...     def __init__(self, *args, **kwargs):
...         super().__init__(*args, **kwargs)
...         self.val_to_keys = defaultdict(list)
...     def __setitem__(self, key, value):
...         super().__setitem__(key, value)
...         self.val_to_keys[value].append(key)
...     def get_keys_for_val(self, value):
...         return self.val_to_keys[value]
... 
>>> d = TwoWayDict()
>>> d['a'] = 1
>>> d['b'] = 1
>>> d.get_keys_for_val(1)
['a', 'b']

为插入增加了极小的开销,但您保持了恒定的查找时间,除了现在是双向查找。不需要在每次需要时从头构造反向映射。只要在你需要的时候存储它并访问它。

此外,这些答案中有许多甚至是不正确的,因为很明显,许多人可能具有相同的年龄,但他们只返回第一个匹配的键,而不是所有的键。

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

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)

这也适用于多个值。

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