This software provides a defaultdict extension that works for dictionaries containing multiple levels of nesting.
Creating a nested_dict is straightforward. Once you have imported the module, you can declare the dictionary and its levels as follows:
nd = nested_dict()
nd["a"]["b"]["c"] = 311
nd["d"]["e"] = 311
Each time you access a nested level, it is created automatically. In the above example, accessing nd["a"]["b"]["c"] for the first time creates the dictionary {"a": {"b": {"c": 311}}}.
Nested_dict also extends collections.defaultdict beyond simple dictionary creation. You can create dictionaries of lists, sets, or other collections with a specified level of nesting using slightly different syntax.
First, you can use the old-fashioned way of creating a dictionary with ugly syntax:
d = dict()
d.setdefault("1st group", []).append(3)
d.setdefault("2nd group", []).append(5)
d.setdefault("2nd group", []).append(8)
d.setdefault("1st group", []).append(4)
d.setdefault("2nd group", []).append(5)
Alternatively, you can use the collections.defaultdict module for easy list creation:
from collections import defaultdict
dd = defaultdict(list)
dd["1st group"].append(3)
dd["2nd group"].append(5)
dd["2nd group"].append(8)
dd["1st group"].append(4)
dd["2nd group"].append(5)
Finally, you can create nested dictionaries that automatically create lists or other collections when required:
from nested_dict import nested_dict
nd = nested_dict(2, list)
nd["1st group"]["subset a"].append(3)
nd["2nd group"]["subset a"].append(5)
nd["2nd group"]["subset b"].append(8)
nd["1st group"]["subset a"].append(4)
nd["2nd group"]["subset b"].append(5)
By specifying two levels of nesting and a list object, we create nd as a nested dictionary of lists. Accessing the nested levels automatically creates the required lists. The resulting dictionary, as printed with print(nd), is:
{'1st group': {'subset a': [3, 4]}, '2nd group': {'subset b': [8, 5], 'subset a': [5]}}
Nested_dict also supports other collections, such as sets, with the same ease-of-use.
Other features of nested_dict include auto-vivification of nested dictionaries and the ability to specify a collection type at initialization.
In conclusion, nested_dict is a valuable addition to any Python developer's toolbox, providing powerful tools for the creation and manipulation of complex data structures.
Version 1.0.8: N/A