Table of contents
Implement code functionality

How to loop through a dictionary in Python

May 30, 2025
 ・ by  
Claude and the Anthropic Team
Table of contents
H2 Link Template
Try Claude

Dictionaries in Python store key-value pairs that let you organize and access data efficiently. Understanding how to iterate through dictionaries unlocks powerful ways to process data structures and solve real-world programming challenges.

This guide covers essential dictionary looping techniques, practical tips, and debugging strategies, with code examples created using Claude, an AI assistant built by Anthropic.

Basic iteration through a dictionary

my_dict = {"apple": 1, "banana": 2, "cherry": 3}
for key in my_dict:
    print(f"Key: {key}, Value: {my_dict[key]}")
Key: apple, Value: 1
Key: banana, Value: 2
Key: cherry, Value: 3

The code demonstrates the most straightforward way to loop through a Python dictionary using a for loop. This method directly iterates over the dictionary's keys, which Python automatically provides when you use a dictionary in a loop context.

While this approach works, it requires an extra step to access values by using the key as an index (my_dict[key]). This makes the code slightly less efficient than alternative methods, especially when dealing with large dictionaries or performance-critical applications. The main advantages of this method include:

  • Intuitive syntax that mirrors how we conceptually think about dictionaries
  • Direct access to keys for operations that primarily focus on key manipulation
  • Compatibility with older Python versions

Common dictionary iteration methods

Python's dictionary methods keys(), values(), and items() provide more explicit and efficient ways to access dictionary components than basic iteration.

Using the keys() method explicitly

my_dict = {"apple": 1, "banana": 2, "cherry": 3}
for key in my_dict.keys():
    print(f"The key is: {key}")
The key is: apple
The key is: banana
The key is: cherry

The keys() method provides explicit access to dictionary keys as a view object. While this approach achieves the same result as basic iteration, it makes the code's intent clearer to other developers reading your code.

  • The method returns a dynamic view of the dictionary's keys that automatically updates when the dictionary changes
  • It enables you to store the keys in a separate variable for repeated use without accessing the dictionary again
  • This approach particularly helps when you need to perform operations exclusively on keys or compare keys across different dictionaries

The performance remains virtually identical to basic iteration since Python optimizes both approaches under the hood. Choose this method when you want to emphasize that you're specifically working with dictionary keys in your code.

Looping through values with the values() method

my_dict = {"apple": 1, "banana": 2, "cherry": 3}
for value in my_dict.values():
    print(f"The value is: {value}")
The value is: 1
The value is: 2
The value is: 3

The values() method provides direct access to a dictionary's values without needing to reference their keys. This approach streamlines your code when you only need to work with the stored data rather than the keys that organize it.

  • The method returns a view object that dynamically updates whenever the dictionary changes
  • It's more memory efficient than creating a separate list of values
  • Python optimizes the iteration process behind the scenes for better performance

When you call my_dict.values(), Python creates an iterator that yields each value in sequence. This eliminates the need to use bracket notation or maintain a separate counter variable while looping through the dictionary.

Unpacking key-value pairs with the items() method

my_dict = {"apple": 1, "banana": 2, "cherry": 3}
for key, value in my_dict.items():
    print(f"{key} has a value of {value}")
apple has a value of 1
banana has a value of 2
cherry has a value of 3

The items() method provides the most elegant way to access both keys and values simultaneously during dictionary iteration. It returns each key-value pair as a tuple that you can unpack directly in the for loop statement.

  • Python automatically unpacks the tuple into the variables key and value at each iteration
  • This approach eliminates the need to use bracket notation or multiple method calls
  • The syntax reads naturally and makes your code's intent immediately clear

While items() creates a view object like keys() and values(), it maintains efficiency by not copying the dictionary data. The method particularly shines when you need to perform operations that depend on both the key and its corresponding value.

Advanced dictionary operations

Building on these foundational iteration methods, Python dictionaries offer powerful features for transforming, viewing, and filtering data structures to solve complex programming challenges.

Creating a new dictionary with dictionary comprehension

my_dict = {"apple": 1, "banana": 2, "cherry": 3}
doubled_values = {k: v*2 for k, v in my_dict.items()}
print(doubled_values)
{'apple': 2, 'banana': 4, 'cherry': 6}

Dictionary comprehension offers a concise way to create new dictionaries by transforming existing ones. The syntax {k: v*2 for k, v in my_dict.items()} creates a new dictionary that doubles each value while keeping the original keys intact.

  • The expression before for (k: v*2) defines how to construct each new key-value pair
  • The iteration part (for k, v in my_dict.items()) works through the source dictionary
  • Python applies the transformation to each element automatically

This approach proves more readable and efficient than traditional loops when performing straightforward dictionary transformations. You'll often use it for data processing tasks like unit conversion or applying calculations across datasets.

Working with dynamic dictionary view objects

my_dict = {"apple": 1, "banana": 2, "cherry": 3}
keys_view = my_dict.keys()
my_dict["date"] = 4
print(f"Updated keys view: {keys_view}")
Updated keys view: dict_keys(['apple', 'banana', 'cherry', 'date'])

Dictionary view objects provide a dynamic window into a dictionary's contents. When you create a view using methods like keys(), values(), or items(), that view automatically reflects any changes made to the original dictionary.

  • The view object keys_view updates automatically when you add the new key "date" to my_dict
  • Views don't create a separate copy of the data. They maintain a live connection to the dictionary
  • This behavior helps prevent data inconsistencies and reduces memory usage in your programs

This dynamic updating proves particularly useful when you need to track dictionary changes across different parts of your code or when working with large datasets where copying data would be inefficient.

Filtering dictionaries during iteration

my_dict = {"apple": 1, "banana": 2, "cherry": 3, "date": 4}
filtered_dict = {k: v for k, v in my_dict.items() if v % 2 == 0}
print(filtered_dict)
{'banana': 2, 'date': 4}

Dictionary comprehension with filtering combines transformation and selection in a single, elegant expression. The code creates a new dictionary containing only key-value pairs where the value is even, using the modulo operator v % 2 == 0 as a filter condition.

  • The if statement at the end acts as a filter, only including pairs that match your condition
  • Python evaluates this condition for each key-value pair during iteration
  • The resulting dictionary preserves the original structure while containing only the filtered elements

This filtering technique proves especially useful when processing data sets where you need to extract specific items based on their values. It offers a more concise and readable alternative to traditional loop-based filtering.

Get unstuck faster with Claude

Claude is an AI assistant created by Anthropic that excels at helping developers write, debug, and understand code. It combines deep technical knowledge with natural conversation to provide clear, actionable guidance.

When you encounter tricky dictionary operations or need help optimizing your Python code, Claude can analyze your specific situation and suggest targeted solutions. It helps explain complex concepts, catches potential bugs, and recommends best practices for your use case.

Start accelerating your Python development today. Sign up for free at Claude.ai to get personalized coding assistance and unblock your development challenges faster.

Some real-world applications

Building on the dictionary operations we've explored, these practical examples demonstrate how Python dictionaries help solve everyday data processing challenges in text analysis and education.

Counting word frequency with the split() method

The split() method transforms text into a list of individual words, enabling us to build a dictionary that tracks how frequently each word appears in a given string.

text = "the quick brown fox jumps over the lazy dog"
word_count = {}

for word in text.split():
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1
        
print(word_count)

This code creates a dictionary to track how many times each word appears in a text string. The split() method breaks the string into individual words that we can process one by one.

The loop checks if each word exists as a key in word_count. When it finds a word for the first time, it adds that word to the dictionary with a count of 1. If the word already exists, it increments its count by 1.

  • Empty dictionary word_count stores word-frequency pairs
  • Default count of 1 for new words using word_count[word] = 1
  • Existing words get incremented through word_count[word] += 1

This pattern forms the foundation for many text analysis tasks where you need to count occurrences of items in a sequence.

Calculating grade averages with nested dictionary iteration

Nested dictionaries enable efficient grade tracking and analysis by storing each student's subject scores as inner dictionaries within a main grade book structure, which we can process using Python's items() method to calculate individual averages.

grade_book = {
    'Alice': {'math': 90, 'science': 82, 'history': 88},
    'Bob': {'math': 85, 'science': 94, 'history': 76},
    'Charlie': {'math': 92, 'science': 88, 'history': 91}
}

for student, subjects in grade_book.items():
    total = sum(subjects.values())
    average = total / len(subjects)
    print(f"{student}'s average grade: {average:.2f}")

This code demonstrates nested dictionary iteration to process student grades efficiently. The outer dictionary uses student names as keys, while inner dictionaries store subject-specific grades. The items() method enables simultaneous access to both the student name and their grade dictionary in a single loop.

  • The subjects.values() call extracts all grades for each student
  • Python's built-in sum() function calculates the total of these grades
  • The len(subjects) counts how many subjects each student takes

The f-string formats the output with two decimal places using :.2f. This creates a clean, readable display of each student's average grade across all their subjects.

Common errors and challenges

Understanding common Python dictionary pitfalls helps you write more reliable code that handles errors gracefully and maintains data integrity during operations.

Preventing KeyError when accessing dictionary keys

A KeyError occurs when you try to access a dictionary key that doesn't exist. This common Python exception can crash your program if not handled properly. The code below demonstrates what happens when requesting a non-existent "email" key from a dictionary.

user_data = {"name": "John", "age": 30}
email = user_data["email"]  # This raises KeyError
print(f"User email: {email}")

The code attempts to directly access a dictionary key that doesn't exist in user_data. Python raises a KeyError because it can't find "email" in the dictionary. Let's examine a safer approach in the code below.

user_data = {"name": "John", "age": 30}
email = user_data.get("email", "Not provided")
print(f"User email: {email}")  # Outputs: User email: Not provided

The get() method provides a safer way to access dictionary values by accepting a default value as its second argument. When Python can't find the requested key, it returns this default instead of raising an error. This approach maintains your code's flow while gracefully handling missing data.

  • Watch for this error when working with user input or external data sources
  • Consider using get() when a key's existence is uncertain
  • The default value helps maintain data consistency in your program

This pattern proves especially valuable when processing data from APIs or user forms where some fields might be optional or empty.

Avoiding RuntimeError when modifying during iteration

Modifying a dictionary while iterating through it can trigger a RuntimeError. This common issue occurs when you attempt to add or remove dictionary items during a for loop. The code below demonstrates how deleting even-numbered values causes Python to raise this error.

numbers = {"a": 1, "b": 2, "c": 3, "d": 4}
for key in numbers:
    if numbers[key] % 2 == 0:
        del numbers[key]  # RuntimeError: dictionary changed during iteration

Python's dictionary iterator expects the dictionary structure to remain stable during iteration. When the code removes items with del, it disrupts this expectation and crashes the loop. The following code demonstrates a safer approach to this operation.

numbers = {"a": 1, "b": 2, "c": 3, "d": 4}
keys_to_delete = [k for k, v in numbers.items() if v % 2 == 0]
for key in keys_to_delete:
    del numbers[key]
print(numbers)  # {'a': 1, 'c': 3}

This solution creates a separate list of keys to remove before modifying the dictionary. The list comprehension [k for k, v in numbers.items() if v % 2 == 0] identifies all keys with even values first. Then a separate loop removes these keys safely because we're not modifying the dictionary during its own iteration.

  • Watch for this error when filtering dictionaries based on their values
  • Be cautious when using del or pop operations inside dictionary loops
  • Consider creating a new dictionary instead of modifying the existing one if you need to preserve the original data

This pattern works well for any situation where you need to remove multiple items from a dictionary based on specific conditions. The two-step approach ensures reliable execution without runtime errors.

Using dict.update() or ** for merging dictionaries

Python dictionaries don't support direct addition with the + operator like lists do. When developers attempt to combine dictionaries using +, Python raises a TypeError. The code below demonstrates this common mistake and its resulting error message.

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 + dict2  # TypeError: unsupported operand type(s) for +

The + operator doesn't understand how to combine dictionary data structures. Python strictly reserves this operator for mathematical addition and sequence concatenation. The code below demonstrates the correct approach to merging dictionaries.

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = {**dict1, **dict2}  # Python 3.5+
print(merged)  # {'a': 1, 'b': 3, 'c': 4}

The double asterisk operator ** unpacks each dictionary's key-value pairs into the new dictionary. When dictionaries share keys, the rightmost dictionary's values take precedence. In this case, dict2's value for key 'b' (3) overwrites dict1's value (2).

  • Watch for this pattern when combining data from multiple sources
  • Consider which dictionary should take precedence for duplicate keys
  • Use dict.update() as an alternative method for dictionary merging

This approach works seamlessly with any number of dictionaries. Simply add more ** expressions to merge additional dictionaries in your preferred order.

Learning or leveling up? Use Claude

Claude combines advanced language understanding with deep programming expertise to serve as your personal coding mentor, helping you master Python's dictionary operations and debug complex data structures. The AI assistant analyzes your code, explains concepts clearly, and suggests targeted improvements to accelerate your development process.

  • Dictionary Debugging: Ask "What's wrong with my dictionary iteration code?" and Claude will identify common issues like KeyError exceptions or incorrect loop patterns.
  • Code Optimization: Ask "How can I make this dictionary code more efficient?" and Claude will suggest improvements like using items() instead of accessing keys separately.
  • Best Practices: Ask "What's the best way to merge these dictionaries?" and Claude will explain modern approaches using the double asterisk operator or update() method.
  • Real-world Examples: Ask "Show me how to count word frequencies in a text file" and Claude will demonstrate practical dictionary applications with clear explanations.
  • Error Resolution: Ask "Why am I getting a RuntimeError in my dictionary loop?" and Claude will explain the issue and provide a working solution.

Experience personalized coding assistance today by signing up at Claude.ai—it's free to get started.

For a more integrated development experience, Claude Code brings AI assistance directly into your terminal, enabling seamless collaboration while you work with Python dictionaries and other complex data structures.

FAQs

Additional Resources

How to concatenate strings in Python

2025-05-22
14 min
 read
Read more

How to use the 'random' module in Python

2025-05-30
14 min
 read
Read more

How to find prime numbers in Python

2025-05-30
14 min
 read
Read more

Leading companies build with Claude

ReplitCognitionGithub CopilotCursorSourcegraph
Try Claude
Get API Access
Copy
Expand