Home >Backend Development >Python Tutorial >How to Recursively Print All Values from a Nested Dictionary in Python?
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.
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.
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!