问题描述
我需要一个字典,对于某些键可能具有相同的名称,并在引用该类型的键时返回值列表。
例如
I need to have a dictionary which might have same names for some keys and return a list of values when referencing the key in that case.For example
print mydict['key']
[1,2,3,4,5,6]
推荐答案
为了保持一致性,字典地图键列出(或设置)值,其中一些可以为空。有一个很好的成语:
For consistency, you should have the dictionary map keys to lists (or sets) of values, of which some can be empty. There is a nice idiom for this:
from collections import defaultdict
d = defaultdict(set)
d["key"].add(...)
(A defaultdict
就像一个正常的字典,但是如果一个键丢失,它将调用您在实例化时传入的参数,并将结果用作默认值,因此这将自动创建一个空如果您要求一个尚未存在的密钥,则可以设置一组值。)
(A defaultdict
is like a normal dictionary, but if a key is missing it will call the argument you passed in when you instantiated it and use the result as the default value. So this will automatically create an empty set of values if you ask for a key which isn't already present.)
如果您需要该对象更像一个字典(即通过 d [key] = ...
设置值),您可以执行以下操作。 但是这可能是一个坏主意,因为它违反了普通的Python语法,很可能会回来再咬你。特别是如果有人必须维护你的代码。
If you need the object to look more like a dictionary (i.e. to set a value by d["key"] = ...
) you can do the following. But this is probably a bad idea, because it goes against the normal Python syntax, and is likely to come back and bite you later. Especially if someone else has to maintain your code.
class Multidict(defaultdict):
def __init__(self):
super(Multidict, self).__init__(set)
def __setitem__(self, key, value):
self[key].add(value)
这篇关于Python有相同名称的字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!