Skip to content

Instantly share code, notes, and snippets.

@KyleJamesWalker
Last active January 4, 2016 05:09
Show Gist options
  • Save KyleJamesWalker/8573350 to your computer and use it in GitHub Desktop.
Save KyleJamesWalker/8573350 to your computer and use it in GitHub Desktop.
Create a default dictionary n levels deep, with support for json.dumps() without the need for a special encoder.
import json
from collections import defaultdict
class NestedDefaultDict(defaultdict):
def __init__(self, depth, default=int, _root=True):
self.root = _root
self.depth = depth
if depth > 1:
cur_default = lambda: NestedDefaultDict(depth - 1,
default,
False)
else:
cur_default = default
defaultdict.__init__(self, cur_default)
def __repr__(self):
if self.root:
return "NestedDefaultDict(%d): {%s}" % (self.depth,
defaultdict.__repr__(self))
else:
return defaultdict.__repr__(self)
# Quick Example
core_data_type = lambda: [0] * 10
test = NestedDefaultDict(3, core_data_type)
test['hello']['world']['example'][5] += 100
print test
print json.dumps(test)
# Code without custom class.
test = defaultdict(lambda: defaultdict(lambda: defaultdict(core_data_type)))
test['hello']['world']['example'][5] += 100
print test
print json.dumps(test)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment