Created
June 17, 2020 20:53
-
-
Save nucklehead/2d29628bb49115f3c30e78c071207775 to your computer and use it in GitHub Desktop.
Python nested defaultdict
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> 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})})})}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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