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
Susan SarandonOriginal
2024-11-27 21:45:12892browse

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}")

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",
    }
}

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

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!

Statement:
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