Last active
June 20, 2019 15:55
-
-
Save disconnect3d/cfb75de54e3a725a2acc2841fd494cff to your computer and use it in GitHub Desktop.
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
In [3]: from collections import UserDict, defaultdict | |
In [4]: class A(UserDict): | |
...: def __getitem__(self, key): | |
...: if key not in self: | |
...: self[key] = defaultdict(lambda: A()) | |
...: return super().__getitem__(key) | |
...: | |
In [6]: a = A() | |
In [7]: a['x']['y']['z'] = 1 | |
In [8]: a | |
Out[8]: {'x': defaultdict(<function A.__getitem__.<locals>.<lambda> at 0x109fa1ae8>, {'y': {'z': 1}})} | |
In [9]: a['a']['b']['c']['d'] | |
Out[9]: {} | |
In [10]: a | |
Out[10]: {'x': defaultdict(<function A.__getitem__.<locals>.<lambda> at 0x109fa1ae8>, {'y': {'z': 1}}), 'a': defaultdict(<function A.__getitem__.<locals>.<lambda> at 0x109fa12f0>, {'b': {'c': defaultdict(<function A.__getitem__.<locals>.<lambda> at 0x10a114158>, {'d': {}})}})} | |
# or... you can just do def A(): return defaultdict(A) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment