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

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github