Search code examples
pythondefaultdict

Python defaultdict: switching default creation on / off?


Is there a way to switch a defaultdict from permissive into strict mode and back again?

Update after first comment: without "trivially" converting to a standard dict, as this may lead to memory problems for dicts with hundreds of millions of entries.

from collections import defaultdict

# population time, be permissive
d = defaultdict(lambda: [])
for i in range(1,10):
    d[i].append(i + 1)

# d.magic()     # magic switch, tell d to be strict
print(d[1])     # OK, exists
print(d[111])   # I'd like to have an error here, please

Solution

  • Just use a regular dictionary instead. Simpler and works, since you only need the "default" functionality within a strictly limited context. In that limited context, use dict.setdefault:

    d = {}
    for i in range(1, 10):
        d.setdefault(i, []).append(i+1)