One-step initialization of defaultdict that appends to list?

后端 未结 5 748
情话喂你
情话喂你 2021-02-19 01:09

It would be convenient if a defaultdict could be initialized along the following lines

d = defaultdict(list, ((\'a\', 1), (\'b\', 2), (\'c\', 3), (         


        
5条回答
  •  渐次进展
    2021-02-19 01:20

    the behavior you describe would not be consistent with the defaultdicts other behaviors. Seems like what you want is FooDict such that

    >>> f = FooDict()
    >>> f['a'] = 1
    >>> f['a'] = 2
    >>> f['a']
    [1, 2]
    

    We can do that, but not with defaultdict; lets call it AppendDict

    import collections
    
    class AppendDict(collections.MutableMapping):
        def __init__(self, container=list, append=None, pairs=()):
            self.container = collections.defaultdict(container)
            self.append = append or list.append
            for key, value in pairs:
                self[key] = value
    
        def __setitem__(self, key, value):
            self.append(self.container[key], value)
    
        def __getitem__(self, key): return self.container[key]
        def __delitem__(self, key): del self.container[key]
        def __iter__(self): return iter(self.container)
        def __len__(self): return len(self.container)
    

提交回复
热议问题