Nested Dictionary Traversal in Python
In Python, nested loops can be used to iterate over nested structures of dictionaries. Below are two common methods:
Option 1: Using multiple loops
You can use multiple loops to iterate through the different nested levels in a dictionary. For example, if you have a dictionary called ‘data’ that contains nested dictionaries and lists, you can use multiple loops to iterate through each level. The following sample code demonstrates how to iterate through a dictionary with two nested levels:
data = {
"key1": {
"subkey1": "value1",
"subkey2": "value2"
},
"key2": {
"subkey3": "value3",
"subkey4": "value4"
}
}
for key1 in data:
for key2 in data[key1]:
print(key1, key2, data[key1][key2])
This example code prints the keys and their corresponding values in each nested dictionary.
Option 2: Using recursion
Using a recursive function to traverse the nested structure of a dictionary. Recursion is a technique of calling a function within itself. The following example code demonstrates how to use a recursive function to traverse a dictionary with arbitrary levels of nesting:
def traverse_dict(data):
for key, value in data.items():
if isinstance(value, dict):
traverse_dict(value)
elif isinstance(value, list):
for item in value:
traverse_dict(item)
else:
print(key, value)
data = {
"key1": {
"subkey1": "value1",
"subkey2": "value2"
},
"key2": {
"subkey3": ["value3", "value4"],
"subkey4": "value5"
}
}
traverse_dict(data)
This sample code prints out the keys and corresponding values in each nested dictionary and list. In the recursive function, it first checks if the current value is a dictionary or a list, if it is, the function continues to call itself recursively; if not, it prints the key and value. This allows for a traversal of the nested structure layer by layer until the innermost key-value pair is found.