Question:
How can one construct a multi-level dictionary with a variable depth, given a list of nested values? Consider the following sample list:
<code>[A][B1][C1] = 1 [A][B1][C2] = 2 [A][B2] = 3 [D][E][F][G] = 4</code>
The desired output is a multi-level dictionary resembling the following structure:
<code>A --B1 -----C1 = 1 -----C2 = 1 --B2 = 3 D --E ----F ------G = 4</code>
Solution:
Using the defaultdict
from the collections
module, one can dynamically create nested dictionaries without the need for hardcoding insertion statements. The defaultdict
returns a default value when an existing key is not found. Here's how it can be implemented:
<code class="python">from collections import defaultdict # Define a function to create a nested dictionary with any level of depth nested_dict = lambda: defaultdict(nested_dict) # Create the nested dictionary using the nested_dict function nest = nested_dict() # Populate the nested dictionary with the given data nest[0][1][2][3][4][5] = 6 print(nest)</code>
This code will create a nested dictionary with a depth of 7, where the value for the key [0][1][2][3][4][5]
is set to 6. The nested dictionary can be accessed using the same key structure, allowing for dynamic creation and retrieval of data at various levels.
The above is the detailed content of How to Construct a Multi-Level Dictionary with Variable Depth Given a Nested List?. For more information, please follow other related articles on the PHP Chinese website!