Python iterate dictionary key-value | Example code

Simple for loop is enough to iterate dictionary key-value in Python. Get key and use those keys to access the 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 over 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

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

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.