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
Within the function:
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!