How to iterate over Python dictionaries using 'for' loops?

Better Stack Team
Updated on January 26, 2023

Let’s assume the following dictionary:

 
my_dictionary = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3'
}

There are three main ways you can iterate over the dictionary.

Iterate over keys

If you iterate over a dictionary the same way you are iterating over a list, you will notice, that you are iterating over dictionary keys:

 
for k in my_dictionary:
    print(k)
 
key1
key2
key3

This is basically the same as using the my_dictionary.keys() as the iterable in the for loop.

You can always use the k to access the value:

 
for k in my_dictionary.keys():
    print(my_dictionary[k])
 
value1
value2
value3

Iterate over values

If you want to iterate over dictionary values instead of dictionary keys, you can use the my_dictionary.values() as iterable in the for loop:

 
for v in my_dictionary.values():
    print(v)
 
value1
value2
value3

Iterate over both keys and values

To iterate over both keys and values, you can use the following syntax:

 
for k, v in my_dictionary.items():
    print(k + ': ' + v)
 
key1: value1
key2: value2
key3: value3
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack