Python – Loop Dictionaries

Welcome to The Coding College, where we simplify coding concepts for all learners! In this tutorial, we’ll explore looping through dictionaries in Python. Understanding how to efficiently iterate over dictionaries is a vital skill for handling data dynamically in Python.

Why Loop Through Dictionaries?

Dictionaries are Python’s key-value pair data structures. You often need to loop through them to access, modify, or process their data. Python offers several ways to iterate over dictionaries, depending on whether you need keys, values, or both.

Looping Through Keys

By default, a for loop iterates over the keys of a dictionary.

Example:

person = {"name": "Alice", "age": 25, "city": "New York"}  

# Loop through keys  
for key in person:  
    print(key)  

Output:

name  
age  
city  

Alternative Method: Using keys()

The keys() method explicitly retrieves the keys.

for key in person.keys():  
    print(key)  

Looping Through Values

To loop through the values of a dictionary, use the values() method.

Example:

person = {"name": "Alice", "age": 25, "city": "New York"}  

# Loop through values  
for value in person.values():  
    print(value)  

Output:

Alice  
25  
New York  

Looping Through Key-Value Pairs

To iterate through both keys and values, use the items() method.

Example:

person = {"name": "Alice", "age": 25, "city": "New York"}  

# Loop through key-value pairs  
for key, value in person.items():  
    print(f"{key}: {value}")  

Output:

name: Alice  
age: 25  
city: New York  

Using a Loop to Modify Dictionary Values

You can loop through a dictionary and modify its values directly.

Example: Incrementing Numeric Values

inventory = {"apples": 10, "bananas": 20, "oranges": 15}  

# Increase all values by 5  
for key in inventory:  
    inventory[key] += 5  

print(inventory)  

Output:

{'apples': 15, 'bananas': 25, 'oranges': 20}  

Nested Dictionaries

When working with nested dictionaries, you can use nested loops to access all the data.

Example:

people = {  
    "person1": {"name": "Alice", "age": 25},  
    "person2": {"name": "Bob", "age": 30}  
}  

# Loop through nested dictionaries  
for person, details in people.items():  
    print(f"{person}:")  
    for key, value in details.items():  
        print(f"  {key}: {value}")  

Output:

person1:  
  name: Alice  
  age: 25  
person2:  
  name: Bob  
  age: 30  

Best Practices

  1. Choose the Right Method: Use keys(), values(), or items() based on the data you need to access.
  2. Avoid Modifying While Iterating: Avoid adding or removing keys during iteration to prevent runtime errors. Instead, create a new dictionary or list if modifications are needed.
  3. Handle Large Data Efficiently: For large dictionaries, consider using dictionary comprehensions for better readability and performance.

Practice Exercises

Exercise 1: Loop Through Keys

Given the dictionary:

car = {"brand": "Toyota", "model": "Corolla", "year": 2020}  
  • Write a loop to print all the keys.

Exercise 2: Modify Values

Given the dictionary:

scores = {"math": 80, "science": 85, "english": 78}  
  • Write a loop to increase each score by 10.

Exercise 3: Nested Dictionary

Given the nested dictionary:

students = {  
    "student1": {"name": "John", "grade": "A"},  
    "student2": {"name": "Emma", "grade": "B"}  
}  
  • Write a loop to print each student’s name and grade.

Why Learn with The Coding College?

At The Coding College, we provide tutorials that break down complex programming concepts into simple, actionable steps. Looping through dictionaries is a crucial skill for data management and automation in Python.

Conclusion

Python makes it easy to loop through dictionaries, whether you’re working with keys, values, or both. By mastering these techniques, you’ll be better equipped to handle real-world data processing tasks.

Leave a Comment