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

How Can I Recursively Print Key-Value Pairs from a Nested Dictionary in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 06:30:11194browse

How Can I Recursively Print Key-Value Pairs from a Nested Dictionary in Python?

Traversing Nested Dictionaries

In this problem, you have a nested dictionary and want to print all key-value pairs where the value is not a dictionary. Additionally, you need to traverse any nested dictionaries and print their key-value pairs recursively.

You could attempt a solution with multiple nested loops, but this approach won't scale as you encounter more levels of nesting. The key is to use recursion.

Recursive Solution

  1. Define the myprint function that takes a dictionary as input.
  2. Within the function:

    • Iterate over the dictionary's key-value pairs.
    • If the current value is a dictionary, call myprint recursively on that dictionary.
    • If the value is not a dictionary, print the key-value pair in the desired format.

Here's an implementation:

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

Usage

To use this recursive solution, simply pass your nested dictionary to the myprint function. For example:

d = {
    'xml': {
        'config': {
            'portstatus': {'status': 'good'},
            'target': '1'
        },
        'port': '11'
    }
}
myprint(d)

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

The above is the detailed content of How Can I Recursively Print Key-Value Pairs 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