我做了一个函数,它将在字典中查找年龄并显示匹配的名字:
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。我知道这是不正确的,但我不知道如何让它向后搜索。
我意识到已经有很长一段时间了,最初的提问者可能不再需要答案,但如果您实际上可以控制这段代码,那么这些答案都不是好的答案。您只是使用了错误的数据结构。这是双向字典用例的完美说明:
>>> 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']
为插入增加了极小的开销,但您保持了恒定的查找时间,除了现在是双向查找。不需要在每次需要时从头构造反向映射。只要在你需要的时候存储它并访问它。
此外,这些答案中有许多甚至是不正确的,因为很明显,许多人可能具有相同的年龄,但他们只返回第一个匹配的键,而不是所有的键。
这是一个真正的“可逆字典”,基于Adam Acosta的解决方案,但强制val-to-key调用是唯一的,容易从值返回键:
from collections import UserDict
class ReversibleDict(UserDict):
def __init__(self, enforce_unique=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.val_to_keys = {}
self.check_val = self.check_unique if enforce_unique else lambda x: x
def __setitem__(self, key, value):
self.check_val(value)
super().__setitem__(key, value)
self.val_to_keys[value] = key
def __call__(self, value):
return self.val_to_keys[value]
def check_unique(self, value):
assert value not in self.val_to_keys, f"Non unique value '{value}'"
return value
如果你想强制字典值的唯一性,确保set enforce_unique=True。从值中获取键只需做rev_dict(value),从键中调用值只需像往常一样做dict['key'],这里是一个用法示例:
rev_dict = ReversibleDict(enforce_unique=True)
rev_dict["a"] = 1
rev_dict["b"] = 2
rev_dict["c"] = 3
print("full dictinoary is: ", rev_dict)
print("value for key 'b' is: ", rev_dict["b"])
print("key for value '2' is: ", rev_dict(2))
print("tring to set another key with the same value results in error: ")
rev_dict["d"] = 1
我瞥见所有的答案,没有提到简单地使用列表理解?
这个Python的单行解决方案可以返回任意数量的给定值的所有键(在Python 3.9.1中测试):
>>> dictionary = {'george' : 16, 'amber' : 19, 'frank': 19}
>>>
>>> age = 19
>>> name = [k for k in dictionary.keys() if dictionary[k] == age]; name
['george', 'frank']
>>>
>>> age = (16, 19)
>>> name = [k for k in dictionary.keys() if dictionary[k] in age]; name
['george', 'amber', 'frank']
>>>
>>> age = (22, 25)
>>> name = [k for k in dictionary.keys() if dictionary[k] in age]; name
[]