How to iterate over a dictionary in Python

Key takeaways:

  • A dictionary is an unordered, mutable collection of unique keys paired with values that can be of any data type.

  • Python provides multiple ways to iterate through a dictionary, such as using a for loop with keys, the items() method for key-value pairs, and the values() method for values.

  • Iterating over dictionaries is an efficient way to access, manipulate, or display their contents during execution.

In Python, the dictionary is an unordered dataset i.e., a collection of key-value pairs. The dictionary is also known as an associative array or hashmap. The dictionary is mutable, which means that it allows us to make amends to it during execution. The keys stored in a dictionary must be unique, and the values stored in the dictionary can be of any data type. Dictionary stores data in such a way that it allows us to perform different operations, e.g., insertion and deletion, in an efficient way.

Methods to iterate over a dictionary

In Python, we have multiple ways to iterate over a dictionary. Some of these include, but are not limited to, the following:

  1. Iterating over keys

  2. Iterating over values

  3. Iterating over key-value pairs

  4. Using dictionary methods (keys(), values(), items())

  5. Iterating with index and keys/values (enumerate)

  6. Iterating in sorted order

  7. Nested dictionary iteration

  8. Iterating using map() and dict.get

  9. Iterating using the zip() function

  10. Iteration by unpacking

1. Iterating over keys

By default, iterating over a dictionary directly yields its keys.

my_dict = {'a': 1, 'b': 2, 'c': 3}
# Default iteration
for key in my_dict:
print(key)

2. Iterating over values

If you want to access only the values in the dictionary, you can use the values() method.

my_dict = {'a': 1, 'b': 2, 'c': 3}
# Using values() to iterate over values
for value in my_dict.values():
print(value)

3. Iterating over key-value pairs

To access both keys and values during iteration, use the items() method. This method returns a view object that yields key-value tuples.

my_dict = {'a': 1, 'b': 2, 'c': 3}
# Using items() to iterate over key-value pairs
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")

4. Using dictionary methods (keys(), values(), items())

The dictionary methods keys(), values(), and items() offer flexibility in iteration.

  • keys(): Iterates over keys (default behavior).

  • values(): Iterates over values.

  • items(): Iterates over key-value pairs.

my_dict = {'a': 1, 'b': 2, 'c': 3}
print(list(my_dict.keys())) # ['a', 'b', 'c']
print(list(my_dict.values())) # [1, 2, 3]
print(list(my_dict.items())) # [('a', 1), ('b', 2), ('c', 3)]

5. Iterating with index and keys/values (enumerate)

You can combine enumerate with dictionary iteration to access both the index and keys/values.

my_dict = {'a': 1, 'b': 2, 'c': 3}
# Using enumerate with keys
for index, key in enumerate(my_dict):
print(f"Index: {index}, Key: {key}")
# Using enumerate with values
for index, value in enumerate(my_dict.values()):
print(f"Index: {index}, Value: {value}")

6. Iterating in sorted order

You can iterate over a dictionary in a sorted order of its keys or values using the sorted() function.

my_dict = {'a': 1, 'b': 2, 'c': 3}
# Sorting keys
for key in sorted(my_dict):
print(f"Key: {key}, Value: {my_dict[key]}")
# Sorting values (sort by dictionary values)
for key in sorted(my_dict, key=my_dict.get):
print(f"Key: {key}, Value: {my_dict[key]}")

7. Nested dictionary iteration

When dealing with nested dictionaries, you can use nested loops to iterate through both outer and inner dictionaries.

nested_dict = {'a': {'x': 1, 'y': 2}, 'b': {'x': 3, 'y': 4}}
for outer_key, inner_dict in nested_dict.items():
print(f"Outer Key: {outer_key}")
for inner_key, value in inner_dict.items():
print(f" Inner Key: {inner_key}, Value: {value}")

8. Iterating using map() and dict.get

The map() function can be used to apply a function to each key in the dictionary, and you can use dict.get to fetch the corresponding value.

# Iterating with map() and dict.get
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Using map to print each key-value pair
list(map(lambda key: print(f"Key: {key}, Value: {my_dict.get(key)}"), my_dict))

9. Iterating using the zip() function

The zip() function can pair keys and values for iteration. This method works by zipping the keys() and values() views.

my_dict = {'a': 1, 'b': 2, 'c': 3}
# Using zip to iterate over keys and values
for key, value in zip(my_dict.keys(), my_dict.values()):
print(f"Key: {key}, Value: {value}")

10. Iteration by unpacking

Python allows dictionary unpacking using the ** operator, which can be used to pass key-value pairs to a function or create a new dictionary.

my_dict = {'a': 1, 'b': 2, 'c': 3}
# Unpacking a dictionary to create a new one
new_dict = {**my_dict, 'd': 4}
print(new_dict)
# Using unpacking in a function
def print_items(**kwargs):
for key, value in kwargs.items():
print(f"Key: {key}, Value: {value}")
# Unpacking the dictionary into the function
print_items(**my_dict)

Learn the basics with our engaging course!

Start your coding journey with the“Learn Python” course—the perfect course for absolute beginners! Whether you’re exploring coding as a hobby or building a foundation for a tech career, this course is your gateway to mastering Python—the most beginner-friendly and in-demand programming language. With simple explanations, interactive exercises, and real-world examples, you’ll confidently write your first programs and understand Python essentials. Our step-by-step approach ensures you grasp core concepts while having fun along the way. Join now and start your Python journey today—no prior experience is required!

Conclusion

Python offers multiple methods for iterating over dictionaries, including iterating over keys, key-value pairs, or just values. These techniques provide flexibility depending on the use case, making dictionaries a powerful tool for managing structured data.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the fastest way to iterate over a dictionary in Python?

The fastest way to iterate over a dictionary in Python is using the items() method, which returns both keys and values in each iteration, avoiding extra lookups.

Example using items() (fastest):
for key, value in my_dict.items():
    # Do something with key and value

This method is generally faster than iterating over keys() and performing an additional lookup for values like this:

for key in my_dict.keys():
    value = my_dict[key] 
    # Do something with key and value

Why items() is usually faster:

  • When using items(), Python iterates directly over both the key and the value in one step, avoiding the second dictionary lookup needed with keys().

What does `dict()` do in Python?

The dict() function in Python creates a new dictionary object.

Various ways to create a dictionary:

  • dict(): Creates an empty dictionary.
  • dict(key1=value1, key2=value2, ...): Creates a dictionary with initial key-value pairs.
  • dict(iterable): Converts an iterable of key-value pairs (such as a list of tuples) into a dictionary.

Can keys repeat in a dictionary in Python?

No, keys in a Python dictionary cannot repeat. Each key within a dictionary must be unique.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved