🔄 Looping Dictionaries

Iterating through dictionaries is essential for data processing, analysis, and transformation tasks. Python provides several powerful methods to loop through dictionary content, each designed for specific scenarios and performance requirements.

# Basic dictionary iteration
student_grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78}

# Loop through keys
for student in student_grades:
    print(f"{student}: {student_grades[student]}")

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

🎯 Iterating Through Keys

Looping through dictionary keys provides access to identifiers while allowing value lookup when needed. The default iteration behavior gives you keys directly, making this the most common iteration pattern.

inventory = {'apples': 50, 'bananas': 30, 'oranges': 25}

# Default iteration through keys
for item in inventory:
    print(f"Item: {item}, Stock: {inventory[item]}")

# Explicit keys() method
for item in inventory.keys():
    print(f"Available: {item}")

⚡ Iterating Through Values

Value-focused iteration enables direct data processing without concern for key information. This approach works perfectly for mathematical operations, data analysis, and content manipulation.

test_scores = {'math': 85, 'science': 92, 'english': 78}

# Calculate average score
total = sum(test_scores.values())
average = total / len(test_scores)
print(f"Average score: {average}")

# Find highest score
highest = max(test_scores.values())
print(f"Highest score: {highest}")

🚀 Iterating Through Key-Value Pairs

The items() method provides simultaneous access to both keys and values, enabling comprehensive data processing in a single loop. Here we process complete information without additional lookups.

user_settings = {'theme': 'dark', 'font_size': 14, 'notifications': True}

# Process all settings
for setting, value in user_settings.items():
    print(f"Setting {setting} is set to {value}")

# Conditional processing
for setting, value in user_settings.items():
    if isinstance(value, bool):
        print(f"{setting}: {'enabled' if value else 'disabled'}")

📊 Dictionary Iteration Methods Comparison

MethodReturnsMemory UsageUse Case
for key in dictKeys onlyLowKey-based processing
dict.keys()Keys viewLowExplicit key iteration
dict.values()Values onlyLowData analysis
dict.items()Key-value pairsMediumComplete processing

🔄 Filtering During Iteration

Combining iteration with conditional logic enables selective processing and data transformation. The code demonstrates filtering students based on grade thresholds during iteration.

grades = {'Alice': 95, 'Bob': 67, 'Charlie': 89, 'Diana': 72}

# Find students above threshold
passing_students = []
for student, grade in grades.items():
    if grade >= 70:
        passing_students.append(student)

print("Passing students:", passing_students)

# Process only high performers
for student, grade in grades.items():
    if grade >= 90:
        print(f"⭐ {student}: {grade} (Excellent!)")

📚 Dictionary Comprehensions with Iteration

Dictionary comprehensions combine iteration with transformation in concise expressions. Notice how we create new dictionaries by processing existing data during iteration.

prices = {'apple': 1.20, 'banana': 0.80, 'orange': 1.50}

# Apply discount
discounted = {item: price * 0.9 for item, price in prices.items()}
print("Discounted prices:", discounted)

# Filter and transform
expensive = {item: price for item, price in prices.items() if price > 1.0}
print("Expensive items:", expensive)

🌟 Nested Dictionary Iteration

Working with nested dictionaries requires systematic approaches to access multi-level data structures. The implementation shows iterating through hierarchical data safely.

company = {
    'engineering': {'employees': 15, 'budget': 120000},
    'marketing': {'employees': 8, 'budget': 80000},
    'sales': {'employees': 12, 'budget': 60000}
}

# Iterate through departments
for dept, info in company.items():
    print(f"{dept}: {info['employees']} employees")
    
# Calculate totals
total_employees = sum(info['employees'] for info in company.values())
print(f"Total employees: {total_employees}")

💡 Practical Applications

Data Analysis

Dictionary iteration enables quick data analysis and reporting for business intelligence tasks.

sales_data = {'Q1': 45000, 'Q2': 52000, 'Q3': 48000, 'Q4': 61000}

# Generate sales report
for quarter, sales in sales_data.items():
    percentage = (sales / sum(sales_data.values())) * 100
    print(f"{quarter}: ${sales:,} ({percentage:.1f}%)")

Configuration Processing

Settings validation and processing benefit from systematic iteration through configuration dictionaries.

config = {'debug': True, 'port': 8080, 'host': 'localhost'}

# Validate configuration
required = ['host', 'port']
for setting in required:
    if setting not in config:
        print(f"Missing required setting: {setting}")

Data Transformation

Converting between data formats requires iteration to restructure dictionary content appropriately.

# Convert to list format
user_data = {'name': 'John', 'age': 30, 'city': 'Boston'}
formatted = [f"{key}: {value}" for key, value in user_data.items()]
print("Formatted data:", formatted)

⚠️ Iteration Best Practices

Safe Modification During Iteration

Modifying dictionaries during iteration requires careful approaches to avoid runtime errors. We collect keys first to ensure safe modification.

scores = {'Alice': 85, 'Bob': 65, 'Charlie': 92}

# Safe way to modify during iteration
to_update = []
for student, score in scores.items():
    if score < 70:
        to_update.append(student)

for student in to_update:
    scores[student] += 10  # Grade curve

print("Updated scores:", scores)

Performance Considerations

Different iteration methods have varying performance characteristics depending on dictionary size and operation type.

large_dict = {f"key_{i}": i for i in range(1000)}

# Efficient value processing
total = sum(large_dict.values())  # Fast for large dictionaries

# Memory-efficient key checking
found_keys = [key for key in large_dict if key.endswith('_100')]
print("Found keys:", len(found_keys))

Hands-on Exercise

Create a function that finds the student with the highest grade in a given subject. Loop through the student grades and return the name of the top student.

python
def find_top_student(students, subject):
    # TODO: Find the student with the highest grade in the given subject
    # TODO: Return the student's name
    pass

# Test data
students = {
    'Alice': {'math': 85, 'science': 92},
    'Bob': {'math': 78, 'science': 88},
    'Charlie': {'math': 91, 'science': 85}
}

top_math = find_top_student(students, 'math')
top_science = find_top_student(students, 'science')

print(f"Best in math: {top_math}")
print(f"Best in science: {top_science}")

Solution and Explanation 💡

Click to see the complete solution
def find_top_student(students, subject):
    top_student = None
    highest_grade = 0
    
    # Loop through all students and their grades
    for student_name, grades in students.items():
        if subject in grades:
            if grades[subject] > highest_grade:
                highest_grade = grades[subject]
                top_student = student_name
    
    return top_student

# Test data
students = {
    'Alice': {'math': 85, 'science': 92},
    'Bob': {'math': 78, 'science': 88},
    'Charlie': {'math': 91, 'science': 85}
}

top_math = find_top_student(students, 'math')
top_science = find_top_student(students, 'science')

print(f"Best in math: {top_math}")
print(f"Best in science: {top_science}")

Key Learning Points:

  • 📌 items() method: Use dict.items() to get both keys and values in a loop
  • 📌 Variable tracking: Keep track of the best result while iterating
  • 📌 Nested access: Access values within nested dictionaries using bracket notation
  • 📌 Comparison logic: Use if statements to find maximum values during iteration

Learn more about dictionary copies to understand creating independent copies of dictionary data for safe manipulation.

Test Your Knowledge

Test what you've learned about looping through dictionaries:

What's Next?

Now that you can iterate through dictionaries effectively, you're ready to learn about creating dictionary copies. Understanding copying techniques is essential for safe data manipulation and avoiding unexpected changes.

Ready to continue? Check out our lesson on Dictionary Copies.

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent