How to iterate over Python dictionaries

Iterating over dictionaries using ‘for’ loops is a common task in Python programming. To do this, you can use the built-in ‘for’ loop in Python, which allows you to iterate over the keys of a dictionary.

Python 3.x

Example 1: Iterating over a dictionary using keys

my_dict = {'name': 'Sam', 'age': 30, 'gender': 'male'}

for key in my_dict:
    print(key, my_dict[key])

Output:

name Sam
age 30
gender male

Example 2: Iterating over a dictionary using items

my_dict = {'name': 'Sam', 'age': 30, 'gender': 'male'}

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

Output:

name Sam
age 30
gender male

In both examples, we have a dictionary with three key-value pairs. The ‘for’ loop iterates over the keys in the first example and the key-value pairs in the second example.

The output shows the key and the corresponding value for each key-value pair in the dictionary.

Here’s an example that uses a dictionary with an array of data:

my_dict = {'fruits': ['apple', 'banana', 'orange'], 'vegetables': ['carrot', 'spinach', 'celery']}

for key, value in my_dict.items():
    print(key)
    for item in value:
        print('-', item)

Output:

fruits
- apple
- banana
- orange
vegetables
- carrot
- spinach
- celery

In this example, we have a dictionary with two keys: ‘fruits’ and ‘vegetables’. The values for each key are arrays of strings.

The ‘for’ loop iterates over the key-value pairs in the dictionary. For each key-value pair, the code first prints the key, and then iterates over the array of values using another ‘for’ loop.

For each value in the array, the code prints a dash (‘-‘) followed by the value itself. The output shows each key followed by a list of the corresponding values.

Let’s look the same with Python 2.x. In Python 2.x, we use the iteritems() method instead of items() to iterate over the key-value pairs in the dictionary.

Python 2.x

my_dict = {‘fruits’: [‘apple’, ‘banana’, ‘orange’], ‘vegetables’: [‘carrot’, ‘spinach’, ‘celery’]}

my_dict = {'fruits': ['apple', 'banana', 'orange'], 'vegetables': ['carrot', 'spinach', 'celery']}

for key, value in my_dict.iteritems():
    print key
    for item in value:
        print '-', item

Output:

fruits
- apple
- banana
- orange
vegetables
- carrot
- spinach
- celery