Last active
March 5, 2021 15:19
-
-
Save tomschr/4404b1b33bd5c3558398f5ee140fb7c5 to your computer and use it in GitHub Desktop.
Nested dictionaries
This file contains 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
""" | |
The "ddict" is able to create nested structures. With the help of "defaultdict", | |
it creates arbitrary levels of "dict"-like objects. | |
Run the doctests with: | |
$ python3 -m doctest nested_dict.py | |
>>> d = ddict(a=ddict(b=ddict(c=10)) ) | |
>>> d["a"]["b"]["c"] | |
10 | |
>>> d["a"]["b"]["d"] == {} | |
True | |
>>> d["a"]["b"]["d"] = 42 | |
>>> d["a"]["b"]["d"] | |
42 | |
>>> d["foo"]["bar"]["baz"] == {} | |
True | |
>>> d1 = ddict({"a": {"b": {"c": 10} } }) | |
>>> d2 = ddict() | |
>>> d2["a"]["b"]["c"] = 10 | |
>>> d1 == d2 | |
True | |
# See also | |
https://docs.python.org/3/library/collections.html#defaultdict-objects | |
https://stackoverflow.com/a/19189356 | |
""" | |
from collections import defaultdict | |
from functools import partial | |
def ddict(*args, **kwargs): | |
"""A dict for nested structures.""" | |
def _default(*def_args, **def_kwargs): | |
return defaultdict(_default, *def_args, **def_kwargs) | |
thedict = partial(defaultdict, _default) | |
return thedict(*args, **kwargs) | |
if __name__ == "__main__": | |
d1 = ddict({"a": {"b": {"c": 10} } }) | |
d2 = ddict() | |
d2["a"]["b"]["c"] = 10 | |
assert d1 == d2 | |
print(d1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment