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

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

其他回答

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

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

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

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

最后我用一个函数来做。这种方法可以避免进行完整的循环,直觉告诉我们,它应该比其他解决方案更快。

def get_key_from_value(my_dict, to_find):

    for k,v in my_dict.items():
        if v==to_find: return k

    return None

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

以下是我在一台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())并将它们存储在内存中。

dict_a = {'length': 5, 'width': 9, 'height': 4}

# get the key of specific value 5
key_of_value = list(dict_a)[list(dict_a.values()).index(5)]
print(key_of_value)  # length

# get the key of minimum value
key_min_value = list(dict_a)[list(dict_a.values()).index(sorted(dict_a.values())[0])]
print(key_min_value)  # height

# get the key of maximum value
key_max_value = list(dict_a)[list(dict_a.values()).index(sorted(dict_a.values(), reverse=True)[0])]
print(key_max_value)  # width


mydict = {'george': 16, 'amber': 19}
print mydict.keys()[mydict.values().index(16)]  # Prints george

或者在Python 3.x中:

mydict = {'george': 16, 'amber': 19}
print(list(mydict.keys())[list(mydict.values()).index(16)])  # Prints george

基本上,它将字典的值分离到一个列表中,找到所拥有值的位置,并在该位置获取键。

更多关于Python 3中的keys()和.values():如何从dict获取值列表?