Home > Backend Development > Python Tutorial > How Can I Recursively Iterate Through Nested Dictionaries in Python?

How Can I Recursively Iterate Through Nested Dictionaries in Python?

Susan Sarandon
Release: 2024-11-27 21:45:12
Original
838 people have browsed it

How Can I Recursively Iterate Through Nested Dictionaries in Python?

Recursing through Nested Dictionaries

To iterate through all key-value pairs in a dictionary, including those within nested dictionaries, recursion is required. Here's a recursive function that addresses this problem:

def print_nested_dict(d):
    for key, val in d.items():
        if isinstance(val, dict):
            print_nested_dict(val)
        else:
            print(f"{key} : {val}")
Copy after login

In this function, we recursively explore the dictionary:

  • If the value is another dictionary, the function calls itself with that dictionary.
  • Otherwise, it prints the key-value pair.

Example Usage:

Consider the following dictionary:

d = {
    "xml": {
        "config": {
            "portstatus": {"status": "good"},
            "target": "1",
        },
        "port": "11",
    }
}
Copy after login

Calling print_nested_dict(d) will print the following output:

xml : {config: {portstatus: {status: good}, target: 1}, port: 11}
config : {portstatus: {status: good}, target: 1}
portstatus : {status: good}
target : 1
port : 11
Copy after login

This method effectively traverses through all levels of nested dictionaries, providing a comprehensive view of the data structure.

The above is the detailed content of How Can I Recursively Iterate Through Nested Dictionaries in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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