How to loop through a dictionary in Python
Learn how to loop through a Python dictionary. Explore different methods, tips, real-world applications, and how to debug common errors.

To iterate through a Python dictionary is a common task for data manipulation. With a simple for loop, Python offers several clear and efficient methods to handle these key-value structures.
In this article, you'll explore various techniques to loop through dictionaries. You will find practical tips, real-world applications, and debugging advice to help you master this essential skill.
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]}")--OUTPUT--Key: apple, Value: 1
Key: banana, Value: 2
Key: cherry, Value: 3
The simplest way to loop through a dictionary is to iterate over its keys directly. When you use a for loop on a dictionary, like for key in my_dict, Python automatically iterates through the keys by default. This is the most straightforward approach and is very readable.
To get the corresponding value, you use the key inside the loop with standard dictionary access, like my_dict[key]. While this works perfectly, it's good to know that this method performs a key lookup on each iteration to retrieve the value. For very large dictionaries, this can be slightly less memory-efficient than other methods that fetch the key and value together. Learn more about accessing dictionary values in Python.
Common dictionary iteration methods
To improve on the basic loop, Python provides dedicated dictionary methods—keys(), values(), and items()—for more explicit and often more efficient 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}")--OUTPUT--The key is: apple
The key is: banana
The key is: cherry
Calling my_dict.keys() explicitly returns a special "view object" that provides a dynamic view of the dictionary's keys. While iterating directly over the dictionary (for key in my_dict) gives you the same result, using the keys() method makes your code more self-documenting. It clearly states your intention to work only with the keys.
- This approach is primarily for readability. It doesn't offer a performance benefit over the default key iteration, but it can make your code's purpose clearer to others at a glance.
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}")--OUTPUT--The value is: 1
The value is: 2
The value is: 3
If you only need to work with the values in a dictionary, the values() method is the most direct approach. It returns a view object that contains all the values, letting you loop through them without needing to access the keys at all. This makes your code cleaner and more focused on the task at hand.
- It's especially efficient for operations like summing up all values or checking if a certain value is present in 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}")--OUTPUT--apple has a value of 1
banana has a value of 2
cherry has a value of 3
The items() method is often the best choice when you need both the key and its corresponding value during an iteration. It returns a view object containing key-value pairs, which you can efficiently unpack directly in the for loop.
- This technique, using
for key, value in my_dict.items(), is considered more Pythonic and readable than accessing the value withmy_dict[key]inside the loop. - It's also more performant because it retrieves the key and value together, avoiding a separate lookup for the value on each pass.
Advanced dictionary operations
Building on the basic iteration methods, you can use more advanced techniques to create new dictionaries, filter them on the fly, and work with dynamic views.
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)--OUTPUT--{'apple': 2, 'banana': 4, 'cherry': 6}
Dictionary comprehension offers a concise and readable way to create a new dictionary from an existing iterable. It's a Pythonic shorthand that combines a for loop and the creation of key-value pairs into one line.
- The expression
{k: v*2 for k, v in my_dict.items()}loops through each key-value pair from the original dictionary. - For each pair, it creates a new entry in the
doubled_valuesdictionary, keeping the original keykbut setting the new value tov*2.
This approach is often more efficient than manually creating an empty dictionary and populating it with a traditional loop, especially when using vibe coding to rapidly prototype data transformations. For more foundational knowledge about creating dictionaries in Python, explore different initialization methods.
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}")--OUTPUT--Updated keys view: dict_keys(['apple', 'banana', 'cherry', 'date'])
The methods keys(), values(), and items() don't return a static list of data. Instead, they provide a dynamic view object that stays connected to the original dictionary. If the dictionary is modified, the view reflects those changes in real time.
- As the code shows,
keys_viewwas created before the new item"date": 4was added tomy_dict. Yet, the view automatically updated to include the new key, demonstrating that it's always in sync with the dictionary's current state.
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)--OUTPUT--{'banana': 2, 'date': 4}
You can easily filter a dictionary by adding a conditional if statement to a dictionary comprehension. This lets you create a new dictionary containing only the items that meet your criteria, all in one go.
- In the example, the condition
if v % 2 == 0checks if a value is even using the modulo operator. - Only key-value pairs that pass this test are included in the new
filtered_dict.
This approach is a powerful and Pythonic way to extract a subset of a dictionary in a single, readable line. Similar filtering techniques apply when filtering lists in Python, using list comprehensions with conditions.
Move faster with Replit
Replit is an AI-powered development platform with all Python dependencies pre-installed, so you can skip setup and start coding instantly. Instead of piecing together methods like items(), you can describe the app you want to build and let Agent 4 take it from an idea to a working product, handling everything from code to deployment.
Here are a few examples of practical tools you could build using the dictionary operations from this article:
- A configuration manager that reads a settings dictionary and filters out sensitive keys before displaying them on a dashboard.
- An inventory calculator that iterates through a dictionary of products and their prices to compute the total stock value.
- A user profile generator that transforms a raw data dictionary into a new one with formatted fields, like combining first and last names.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Even with powerful iteration methods, you'll want to watch out for a few common pitfalls to keep your code running smoothly.
Preventing KeyError when accessing dictionary keys
Preventing KeyError when accessing dictionary keys
A KeyError is a frequent runtime error that occurs when you try to access a dictionary key that isn't there. This mistake can halt your program unexpectedly. For example, the following code will fail by trying to access a non-existent 'email' key.
user_data = {"name": "John", "age": 30}
email = user_data["email"] # This raises KeyError
print(f"User email: {email}")
The code attempts a direct lookup for the email key. Because the key is missing, Python immediately raises a KeyError and stops the program. The code below demonstrates a safer way to handle potentially missing keys.
user_data = {"name": "John", "age": 30}
email = user_data.get("email", "Not provided")
print(f"User email: {email}") # Outputs: User email: Not provided
To prevent a KeyError, use the dictionary’s get() method. It safely retrieves a key’s value, but if the key doesn’t exist, it returns a default value you provide instead of crashing your program. In the example, user_data.get("email", "Not provided") returns "Not provided" because the "email" key is missing. This is crucial when working with data where keys might be optional, like API responses or user-submitted forms.
Avoiding RuntimeError when modifying during iteration
Modifying a dictionary while you're iterating over it is a classic mistake that leads to a RuntimeError. Python doesn't allow you to change the size of a dictionary mid-loop, as it disrupts the iteration process. The code below demonstrates this common pitfall.
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
This code fails because del numbers[key] attempts to change the dictionary's size while the for loop is still running on it. Python prohibits this direct modification. The example below demonstrates a safe way to handle this.
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}
The solution is to separate the identification and deletion steps. First, create a new list containing just the keys you want to remove. The example does this efficiently with a list comprehension, storing the keys in keys_to_delete.
Once you have this separate list, you can safely loop through it and delete each key from the original dictionary. This two-step process avoids the error because you're no longer modifying the dictionary while iterating over it directly.
Using dict.update() or ** for merging dictionaries
When you need to combine two dictionaries, your first instinct might be to use the + operator, similar to how you'd merge lists. However, this approach doesn't work for dictionaries and will cause a TypeError. The code below shows this common mistake.
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 + dict2 # TypeError: unsupported operand type(s) for +
Unlike with lists, you can't use the + operator to join dictionaries, which is why the code raises a TypeError. Python needs a clearer instruction for how to merge them. See the correct approach in the example below.
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = {**dict1, **dict2} # Python 3.5+
print(merged) # {'a': 1, 'b': 3, 'c': 4}
To merge dictionaries, use the dictionary unpacking operator **. This syntax, available in Python 3.5+, unpacks key-value pairs from each dictionary into a new one. For example, {**dict1, **dict2} creates a single dictionary. Be aware that if keys overlap, the value from the last dictionary wins. This is useful when combining configurations or datasets, but watch out for unintentionally overwriting data. The dict.update() method offers an alternative for in-place updates. For more detailed techniques on merging dictionaries, explore additional methods and best practices.
Real-world applications
These iteration techniques are fundamental to many real-world data tasks, from counting word frequencies to calculating grade averages.
Counting word frequency with the split() method
By pairing the split() method with a dictionary, you can efficiently iterate through a string of text to count the occurrences of each word.
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 builds a frequency map of words from a string. The for loop iterates over a list of words created by text.split(), which breaks the string apart at each space.
- Inside the loop, an
ifstatement checks if a word is already a key in theword_countdictionary. - If the word exists, its value is incremented with
+= 1. - If it's a new word, it's added to the dictionary with an initial count of 1.
This pattern is a common way to tally items from any sequence. For more advanced techniques on counting words in Python, explore different approaches and optimizations.
Calculating grade averages with nested dictionary iteration
By iterating through a nested dictionary, you can efficiently process structured data, such as calculating each student's average grade from a digital grade book.
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 effectively navigates a dictionary of dictionaries, a common data structure for representing grouped information. The outer loop iterates through each student, while the inner logic focuses on their specific set of grades.
- The key is using
subjects.values()to create a temporary collection of just the numbers, which can be easily processed. - Python's built-in functions,
sum()andlen(), are then applied directly to this collection to find the average without needing another loop.
This pattern is highly efficient for aggregating data from nested structures.
Get started with Replit
Put your new skills to work and build a real tool. Describe what you want to build to Replit Agent, like “build a currency converter using a dictionary for rates” or “create a script that filters a user dictionary.”
Replit Agent will write the code, test for errors, and deploy your app. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



