Iterating over a dictionary in Python allows you to access its keys, values, or both. There are several methods to iterate through a dictionary:
Iterating Over Keys:
You can use a for
loop to iterate directly over the keys of a dictionary:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'Cityville'}
# Iterating over values
for value in my_dict.values():
print(value) # Accessing each value
The values()
method returns a view object containing all the values in the dictionary. You can iterate through this view object to access each value individually.
Iterating Over Both Keys and Values:
To simultaneously iterate over both keys and values, you can use the items()
method:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'Cityville'}
# Iterating over key-value pairs
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}") # Accessing key and value simultaneously
The items()
method returns a view object containing tuples of key-value pairs. By using this method, you can iterate through the tuples to access both keys and their corresponding values at the same time.
Iterating Over Nested Dictionary:
Consider a nested dictionary as follows:
nested_dict = {
'person1': {'name': 'Alice', 'age': 30},
'person2': {'name': 'Bob', 'age': 25}
}
You can iterate through the keys of the outer dictionary (nested_dict
) to access the keys of the inner dictionaries:
# Iterating over keys in the outer dictionary
for person_key in nested_dict:
print(f"Person: {person_key}")
# Accessing inner dictionary using the outer key
inner_dict = nested_dict[person_key]
# Iterating over keys in the inner dictionary
for key in inner_dict:
print(f" {key}: {inner_dict[key]}")
This nested loop first iterates through the keys in the outer dictionary ('person1'
, 'person2'
). For each key, it accesses the corresponding inner dictionary, and then iterates through the keys in the inner dictionary ('name'
, 'age'
) to access their respective values.
You can also use items()
to directly access both keys and values in the nested dictionary:
# Iterating over key-value pairs in the nested dictionary
for person, details in nested_dict.items():
print(f"Person: {person}")
# Iterating over key-value pairs in the inner dictionary
for key, value in details.items():
print(f" {key}: {value}")
This method allows you to iterate through the key-value pairs in both the outer and inner dictionaries simultaneously, providing a cleaner approach to access keys and values in nested structures.