When you want to process all data stored in a Python dictionary (dict) sequentially, use the for statement. Unlike lists, dictionaries contain three distinct elements: “Keys,” “Values,” and “Key-Value Pairs.” Therefore, you need to use different methods depending on your goal.
This article explains three types of loop processing for dictionary data.
1. Looping Through Keys
To retrieve only the “Keys” of a dictionary sequentially, the most common method is to pass the dictionary object directly to the for statement.
Syntax:
for key_variable in dict:
# Process
You can also use the .keys() method to achieve the same result. This is sometimes used when you want to explicitly indicate that you are processing keys.
Example: A program that displays country codes (Keys).
# Dictionary of Country Codes and Names
country_codes = {
"JP": "Japan",
"US": "United States",
"GB": "United Kingdom",
"FR": "France"
}
print("--- Registered Country Codes ---")
# Looping directly through the dictionary extracts keys
for code in country_codes:
print(f"Code: {code}")
# Using .keys() produces the same result
# for code in country_codes.keys():
# print(f"Code: {code}")
Output:
--- Registered Country Codes ---
Code: JP
Code: US
Code: GB
Code: FR
2. Looping Through Values
If you want to extract and process only the “Values” of a dictionary, use the .values() method.
Syntax:
for value_variable in dict.values():
# Process
Example: A program that extracts test scores (Values) for each subject and calculates the total score.
# Dictionary of Subjects and Scores
test_scores = {
"Math": 85,
"Science": 92,
"History": 78,
"English": 88
}
total_score = 0
print("--- Score List ---")
# Loop through only values using .values()
for score in test_scores.values():
print(f"{score} points")
total_score += score
print(f"Total Score: {total_score}")
Output:
--- Score List ---
85 points
92 points
78 points
88 points
Total Score: 343
3. Looping Through Key-Value Pairs (Items)
If you want to extract and process both “Keys” and “Values” simultaneously, use the .items() method. This method returns tuples in the format (key, value), so you specify two variables in the for statement to unpack (expand) and receive them.
Syntax:
for key_variable, value_variable in dict.items():
# Process
Example: A program that displays the product name (Key) and stock count (Value) from inventory management data simultaneously.
# Dictionary of Product Names and Stock Counts
inventory = {
"Laptop": 15,
"Mouse": 50,
"Keyboard": 30,
"Monitor": 8
}
print("--- Inventory Status ---")
# Get Key and Value simultaneously using .items()
for product, count in inventory.items():
status = "In Stock" if count > 10 else "Low Stock"
print(f"Product: {product} | Count: {count} ({status})")
Output:
--- Inventory Status ---
Product: Laptop | Count: 15 (In Stock)
Product: Mouse | Count: 50 (In Stock)
Product: Keyboard | Count: 30 (In Stock)
Product: Monitor | Count: 8 (Low Stock)
Summary
Use one of the following three methods for looping through dictionaries depending on the data you need.
- Need Keys:
for key in d:(ord.keys()) - Need Values:
for value in d.values(): - Need Both:
for key, value in d.items():
In particular, .items() is the most efficient and readable method when you need both data points, as it saves the trouble of searching for the value using the key.
