Skip to content

Python iterate dictionary key-value | Example code

  • by

Simple for loop is enough to iterate dictionary key-value in Python. Get a key and use those keys to access its value of it.

key is just a variable name that will simply loop over the keys in the dictionary, rather than the keys and values.


for key in dict1:
    print(key, dict1.get(key))

Or, if you want to cover both key and value you can use the following:

For Python 3.x:

for key, value in d.items()

Example how to iterate dictionary key-value in Python

Simple example code.

Example 1

dict1 = {1: 'X', 2: 'Y', 3: 'Z'}

for key in dict1:
    print(key, dict1.get(key))

Example 2

dict1 = {1: 'X', 2: 'Y', 3: 'Z'}

for key, value in dict1.items():
    print(key, value)

Output:

Python iterate dictionary key-value

Or you can iterate over the keys and values of a dictionary using a for loop and the .items() method.

my_dict = {'a': 1, 'b': 2, 'c': 3}

# Iterate over the keys and values
for key, value in my_dict.items():
    print(key, value)

Do comment if you have any doubts or suggestions on this Python dictionary code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading