Join our newsletter for the latest updates.

Python Program to Iterate Over Dictionaries Using for Loop

In this example, you will learn to iterate over dictionaries using for loop.

To understand this example, you should have the knowledge of the following Python programming topics:


Example 1: Access both key and value using items()

dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}

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

Output

a juice
b grill
c corn

Example 2: Access both key and value without using items()

dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}

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

Output

a juice
b grill
c corn

However, the more pythonic way is example 1.


Example 3: Access both key and value using iteritems()

dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}

for key, value in dt.iteritems():
    print(key, value)

Output

a juice
b grill
c corn

It works for python 2 versions.


Example 4: Return keys or values explicitly

dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}

for key in dt.keys():
    print(key)

for value in dt.values():
    print(value)

Output

a
b
c
juice
grill
corn

You can use keys() and values() to explicitly return keys and values of the dictionary respectively.