Iterating over dictionaries using ‘for’ loops in Python
Dictionary is an unordered collection of data in the form of key:value pairs separated by commas inside curly brackets.
Unlike sequences, which are iterables that support accessing of elements using integer indexing, dictionaries are indexed by keys. Dictionaries are generally optimized to retrieve values when the key is known.
>>fruits_colors = {'Apple: 'Red', 'Mango’: 'Yellow', 'Kiwi’: 'Brown', 'Grapes’: 'Green'} >>colors["Apple"] 'Red'
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values and also return both keys and values as well. Let’s discuss one by one
Iterate through all keys:
The order of fruits in the code given below may vary every time because the dictionary doesn’t keep track of the insertion order of the (key, value) pairs and thus makes it unordered
#Iterate through all keys in a dictionary
>>fruits_colors = {'Apple: 'Red', 'Mango': 'Yellow', 'Kiwi': 'Brown', 'Grapes': 'Green'} >>print ('List of fruits:\n')
# Iterating over keys
>>for fruit in fruits_colors: print(fruit)
Output:
List of fruits: Apple Kiwi Mango Grapes
The order of fruits in the code given below may vary every time because the dictionary doesn’t keep track of the insertion order of the (key, value) pairs and thus makes it unordered
In order to maintain the order of keys and values in a dictionary, use OrderedDict.
# Iterate through all keys in a dictionary in a specific order
>>from collections import OrderedDict >>fruits_colors = OrderedDict ([('Apple', 'Red'), ('Mango', 'Yellow'), ('Kiwi', 'Brown'),('Grapes', 'Green')]) >>print ('List of fruits:\n')
# Iterating over keys
>>for fruit in fruits_colors: print(fruit)
Output:
List of fruits: Apple Mango Kiwi Grapes
Iterate through all values:
Again, in this case, the order in which the capitals are printed in the below code will change every time because the dictionary doesn’t store them in a particular order.
# Python3 code to iterate through all values in a dictionary
>>fruits_colors = {'Apple': 'Red', 'Mango': 'Yellow', 'Kiwi', 'Brown', 'Grapes': 'Green'} >>print('List of colors:\n')
# Iterating over values
>>for colors in fruits_colors.values(): print(colors)
Output:
List of colors: Red Brown Yellow Green
Iterate through all key, value pairs:
# Iterate through all key, value pairs in a dictionary
>>fruits_colors = {'Apple': 'Red', 'Mango': 'Yellow', 'Kiwi': 'Brown', 'Grapes': 'Green'} >>print('List of fruits and colors:\n')
# Iterating over values
>>for fruit, color in fruits_colors.items(): print(fruit, ":", color)
Output:
List of fruits and colors: Grapes: Green Apple: Red Kiwi: Brown Mango: Yellow