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.

Examples

1. Iterate through items of given dictionary

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 Code Copy

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.

2. Loop through keys in given 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 Code Copy

Output

name
year
expertise

3. Loop through values in given 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 Code Copy

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.

4. Loop through key:value pairs in given 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 Code Copy

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.

Related Tutorials

Code copied to clipboard successfully 👍