Exposing `defaultdict` as a regular `dict`

后端 未结 3 1788
被撕碎了的回忆
被撕碎了的回忆 2020-12-25 11:45

I am using defaultdict(set) to populate an internal mapping in a very large data structure. After it\'s populated, the whole structure (including the mapping) i

相关标签:
3条回答
  • 2020-12-25 11:49

    Once you have finished populating your defaultdict, you can simply create a regular dict from it:

    my_dict = dict(my_default_dict)
    

    One can optionally use the typing.Final type annotation.

    If the default dict is a recursive default dict, see this answer which uses a recursive solution.

    0 讨论(0)
  • 2020-12-25 11:59

    You could make a class that holds a reference to your dict and prevent setitem()

    from collections import Mapping
    
    class MyDict(Mapping):
        def __init__(self, d):
            self.d = d;
    
        def __getitem__(self, k):
            return self.d[k]
    
        def __iter__(self):
            return self.__iter__()
    
        def __setitem__(self, k, v):
            if k not in self.d.keys():
                raise KeyError
            else:
                self.d[k] = v
    
    0 讨论(0)
  • 2020-12-25 12:05

    defaultdict docs say for default_factory:

    If the default_factory attribute is None, this raises a KeyError exception with the key as argument.

    What if you just set your defaultdict's default_factory to None? E.g.,

    >>> d = defaultdict(int)
    >>> d['a'] += 1
    >>> d
    defaultdict(<type 'int'>, {'a': 1})
    >>> d.default_factory = None
    >>> d['b'] += 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'b'
    >>> 
    

    Not sure if this is the best approach, but seems to work.

    0 讨论(0)
提交回复
热议问题