[ACCEPTED]-Exposing `defaultdict` as a regular `dict`-defaultdict

Accepted answer
Score: 60

defaultdict docs say for default_factory:

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

What if you just 3 set your defaultdict's default_factory to 2 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 1 seems to work.

Score: 3

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

my_dict = dict(my_default_dict)

One 3 can optionally use the typing.Final type annotation.

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

Score: 0

You could make a class that holds a reference 1 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
            self.d[k] = v

More Related questions