How to Loop through Python Dictionary?

Loop through Python Dictionary

Dictionary is a collection of items. Each item is a key:value pair. And all the items in a dictionary can be traversed using a looping statement or traversing technique.

To loop through a dictionary, we can use Python for loop. In this tutorial, we will learn how to iterate through key:value pairs of dictionary, or just the keys or just the values.

Example 1: Iterate through Python Dictionary Items

In this example, we will initialize a dictionary with three key:value pairs. We shall use Python For Loop to iterate over this dictionary, and print the keys.

Python Program

myDictionary = {
	"name": "Lini",
	"year": 1989,
	"expertise": "data analytics"}

#iterate through dictionary
for key in myDictionary:
	print(key, '-', myDictionary[key])
Run

Output

name - Lini
year - 1989
expertise - data analytics

All the keys are printed by traversing through the Python dictionary using for loop. And during each iteration, we could access the value corresponding to a key using indexing.

Example 2: Loop through keys of Dictionary

To traverse exclusively through keys, you can use the default for item in iterable statement as shown below.

Python Program

myDictionary = {
	"name": "Lini",
	"year": 1989,
	"expertise": "data analytics"}

#iterate through dictionary
for key in myDictionary:
	print(key)
Run

Output

name
year
expertise

Example 3: Loop through values of Dictionary

To traverse exclusively through values, you can use the default for item in iterable statement as shown below.

Python Program

myDictionary = {
	"name": "Lini",
	"year": 1989,
	"expertise": "data analytics"}

#iterate through dictionary values
for value in myDictionary.values():
	print(value)
Run

Output

Lini
1989
data analytics

In the above example, we have used dict.values(). dict.values() returns iterator over only the values in the dictionary.

Example 4: Loop through key:value pairs of Dictionary

Or you can use for loop, to access both key and value, as shown below.

Python Program

myDictionary = {
	"name": "Lini",
	"year": 1989,
	"expertise": "data analytics"}

#iterate through key:value pairs of dictionary
for key, value in myDictionary.items():
	print(key, ': ', value)
Run

myDictionary.items() returns an iterator that provides access to both key and value.

Output

name :  Lini
year :  1989
expertise :  data analytics

Summary

In this tutorial of Python Examples, we learned how to traverse through the Dictionary items using for loop with the help of well detailed examples.