How to iterate through a dictionary using Python

Syntax:


for key, value in myDict.items():
    print( "{} = {}".format(key, value) )

The ideal way to iterate through a dictionary is using the items method that return the key value pairs. This way the content is accessed in with a O(n) complexity.

Example:

This example creates a dictionary called myDict with 2 key value pairs. The content of the dictionary is written in the output iterating on the elements using a for loop.

# Create the dictionary
myDict = { "key1": 1, "key2": 2 }

# Print the content of the dictionary
for key, value in myDict.items():
    print( "{} = {}".format(key, value) )

The output will be:

key1 = 1
key2 = 2

References:

Python