Home >Backend Development >Python Tutorial >How Can I Recursively Iterate and Print Key-Value Pairs from a Nested Dictionary?

How Can I Recursively Iterate and Print Key-Value Pairs from a Nested Dictionary?

Barbara Streisand
Barbara StreisandOriginal
2024-11-29 17:56:14697browse

How Can I Recursively Iterate and Print Key-Value Pairs from a Nested Dictionary?

Iterating Through Nested Dictionary Values

In this programming scenario, our goal is to traverse a potentially multi-layered dictionary structure and print key-value pairs where the values are not nested dictionaries themselves. If a value happens to be a nested dictionary, we need to recursively explore it and print its key-value pairs as well.

To achieve this, simple iteration techniques may not suffice. Instead, we can harness the power of recursion. Here's a revised function that incorporates recursion to effectively handle nested dictionaries of any depth:

def myprint(d):
    for k, v in d.items():
        if isinstance(v, dict):
            myprint(v)
        else:
            print("{0} : {1}".format(k, v))

By calling myprint with the initial dictionary, the function enters a recursive loop. It visits each key-value pair and checks if the value is a dictionary. If it is, the function calls itself with the value dictionary as the new input, effectively drilling down into any nested levels.

If the value is not a dictionary, the function simply prints the current key-value pair. This process continues until all levels of the dictionary have been traversed.

Here's a demonstration using a sample nested dictionary:

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

myprint(d)

This will produce the desired output:

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

As you can see, the function recursively iterates through the dictionary, printing all non-nested values and drilling down into nested dictionaries until it reaches the leaf nodes.

The above is the detailed content of How Can I Recursively Iterate and Print Key-Value Pairs from a Nested Dictionary?. 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