To iterate over a dictionary of dictionaries in Python, you can use nested `for` loops to iterate through both the outer dictionary and the inner dictionaries. This allows you to access and process each key-value pair in the nested dictionaries.
We can iterate over a dictionary of dictionaries in Python using nested `for` loops. This example demonstrates how to declare and initialize a dictionary of dictionaries, use nested `for` loops to iterate through the outer and inner dictionaries, and print each key-value pair.
For example,
outer_dict
with string keys and integer values.outer_dict = {
'A': {'X': 1, 'Y': 2},
'B': {'Z': 3}
}
# Iterate over the dictionary of dictionaries using nested for loops
print('Iterating over dictionary of dictionaries:')
for outer_key, inner_dict in outer_dict.items():
print(f'Outer Key: {outer_key}')
for inner_key, value in inner_dict.items():
print(f' Inner Key: {inner_key}, Value: {value}')
Iterating over dictionary of dictionaries: Outer Key: A Inner Key: X, Value: 1 Inner Key: Y, Value: 2 Outer Key: B Inner Key: Z, Value: 3
We can iterate over a dynamically created dictionary of dictionaries in Python using nested `for` loops. This example demonstrates how to declare a dictionary of dictionaries, add inner dictionaries dynamically, add key-value pairs to the inner dictionaries, use nested `for` loops to iterate through the outer and inner dictionaries, and print each key-value pair.
For example,
outer_dict
.outer_dict = {}
# Add inner dictionaries dynamically
outer_dict['A'] = {}
outer_dict['B'] = {}
# Add key-value pairs to the inner dictionaries
outer_dict['A']['X'] = 1
outer_dict['A']['Y'] = 2
outer_dict['B']['Z'] = 3
# Iterate over the dictionary of dictionaries using nested for loops
print('Iterating over dictionary of dictionaries:')
for outer_key, inner_dict in outer_dict.items():
print(f'Outer Key: {outer_key}')
for inner_key, value in inner_dict.items():
print(f' Inner Key: {inner_key}, Value: {value}')
Iterating over dictionary of dictionaries: Outer Key: A Inner Key: X, Value: 1 Inner Key: Y, Value: 2 Outer Key: B Inner Key: Z, Value: 3
In this tutorial, we learned How to Iterate Over a Dictionary of Dictionaries in Python language with well detailed examples.