且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以有一个带有同名键的字典吗?

更新时间:2023-01-19 18:51:35

为保持一致性,您应该将字典映射键用于值的列表(或集合),其中一些可以为空.有一个很好的成语:

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):
        if isinstance(value, (self.default_factory)): # self.default_factory is `set`
            super().__setitem__(key, value)
        else:
            self[key].append(value)

我还没有测试过.