Home > Backend Development > Python Tutorial > How to Construct a Multi-Level Dictionary with Variable Depth Given a Nested List?

How to Construct a Multi-Level Dictionary with Variable Depth Given a Nested List?

Patricia Arquette
Release: 2024-10-17 11:10:30
Original
295 people have browsed it

How to Construct a Multi-Level Dictionary with Variable Depth Given a Nested List?

Constructing a Multi-Level Dictionary with Varying Depth

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template