Home >Backend Development >Python Tutorial >How to Recursively Print All Values from a Nested Dictionary in Python?

How to Recursively Print All Values from a Nested Dictionary in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-29 05:31:11647browse

How to Recursively Print All Values from a Nested Dictionary in Python?

Recursive Looping through Nested Dictionary Values

Problem Statement

Given a nested dictionary, the task is to traverse through all its key-value pairs, printing values that are not nested dictionaries. For nested dictionaries, the traversal should continue recursively to print their key-value pairs.

Solution

Utilizing recursion, a function can be defined to perform this task:

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

This function accepts a dictionary as an argument and iterates through its key-value pairs. If a value is not a nested dictionary, it prints the key-value pair. If the value is a dictionary, it recursively calls the myprint function with this new dictionary.

Example

Consider the following dictionary:

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

Calling the myprint function would output:

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

This solution provides a recursive mechanism to loop through all nested dictionary values and print them as desired.

The above is the detailed content of How to Recursively Print All Values from a Nested Dictionary 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