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

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


当前回答

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

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

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

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

其他回答

get_key = lambda v, d: next(k for k in d if d[k] is v)

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

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

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

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

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

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

我认为指出哪些方法是最快的,以及在什么情况下是最快的会很有趣:

以下是我在一台2012年的MacBook Pro上进行的一些测试

def method1(dict, search_age):
    for name, age in dict.iteritems():
        if age == search_age:
            return name

def method2(dict, search_age):
    return [name for name,age in dict.iteritems() if age == search_age]

def method3(dict, search_age):
    return dict.keys()[dict.values().index(search_age)]

profile.run()在每个方法上100,000次的结果:

方法1:

>>> profile.run("for i in range(0,100000): method1(dict, 16)")
     200004 function calls in 1.173 seconds

方法2:

>>> profile.run("for i in range(0,100000): method2(dict, 16)")
     200004 function calls in 1.222 seconds

方法3:

>>> profile.run("for i in range(0,100000): method3(dict, 16)")
     400004 function calls in 2.125 seconds

所以这表明,对于一个小字典,方法1是最快的。这很可能是因为它返回第一个匹配,而不是像方法2那样返回所有匹配(参见下面的注释)。


有趣的是,在我有2700个条目的字典上执行相同的测试,我得到了完全不同的结果(这次运行了10,000次):

方法1:

>>> profile.run("for i in range(0,10000): method1(UIC_CRS,'7088380')")
     20004 function calls in 2.928 seconds

方法2:

>>> profile.run("for i in range(0,10000): method2(UIC_CRS,'7088380')")
     20004 function calls in 3.872 seconds

方法3:

>>> profile.run("for i in range(0,10000): method3(UIC_CRS,'7088380')")
     40004 function calls in 1.176 seconds

这里,方法3要快得多。这表明字典的大小会影响你选择的方法。

注:

方法2返回所有名称的列表,而方法1和3只返回第一个匹配项。 我没有考虑内存使用情况。我不确定方法3是否创建了2个额外的列表(keys()和values())并将它们存储在内存中。

通过“查找”值来查找列表中的键是不容易的。但是,如果知道值,遍历键,就可以按元素在字典中查找值。如果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)