Skip to content

Instantly share code, notes, and snippets.

@nucklehead
Created June 17, 2020 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nucklehead/2d29628bb49115f3c30e78c071207775 to your computer and use it in GitHub Desktop.
Save nucklehead/2d29628bb49115f3c30e78c071207775 to your computer and use it in GitHub Desktop.
Python nested defaultdict
>>> bb = nested_defaultdict({'a':{'b': 1000}})
>>> bb['c']['e']['f']['g'] = 2000
>>> bb
defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'a': defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'b': 1000}), 'c': defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'e': defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'f': defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'g': 2000})})})})
>>> bb['a']['c']['f']['g'] = 3000
>>> bb
defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'a': defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'b': 1000, 'c': defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'f': defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'g': 3000})})}), 'c': defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'e': defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'f': defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'g': 2000})})})})
>>> import json
>>> json.dumps(bb)
'{"a": {"b": 1000, "c": {"f": {"g": 3000}}}, "c": {"e": {"f": {"g": 2000}}}}'
>>> bb = nested_defaultdict()
>>> bb
defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {})
>>> bb['a']['c']['f']['g'] = 3000
>>> bb
defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'a': defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'c': defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'f': defaultdict(<function nested_defaultdict at 0x7fcb514bcb70>, {'g': 3000})})})})
def nested_defaultdict(existing=None, **kwargs):
if existing is None:
existing = {}
if not isinstance(existing, dict):
return existing
existing = {key: nested_defaultdict(val) for key, val in existing.items()}
return defaultdict(nested_defaultdict, existing, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment