Looping Through Dictionaries
tags: #python/documentation/dictionaries
There are three ways to iterate over the items in a dictionary by using a For Loop based on its:
- Keys
- Values
- Key-Value Pair
1. Looping Through all Key-Value Pairs
Python dictionary provides a method called items() that returns an object which contains a list of key-value pairs as tuples in a list. To iterate over all key-value pairs in a dictionary, you can use a for loop to unpack each tuple in the list.
Example:
person = {
'first_name': 'John',
'last_name': 'Doe',
'age': 25,
'favorite_colors': ['blue', 'green'],
'active': True
}
for key, value in person.items():
print(f"{key}: {value}") # f string
first_name: John
last_name: Doe
age: 25
favorite_colors: ['blue', 'green']
active: True
2. Looping through all the keys in a dictionary
You can loop through keys in a dictionary by using a for loop with the keys() method.
for key in dictionary.keys():
print(key)
Note: looping through all keys is the default behaviour when looping through a dictionary -> therefore, a keys() method is not necessary:
for key in dictionary_name:
print(key)
3. Looping through all the values in a dictionary
You can loop through values in a dictionary by using a for loop with the values() method.
for value in dictionary.values():
print(value)