Online Tutorials & Training Materials | STechies.com
Register Login

How to Iterate Through a Dictionary in Python with Example?

08 Feb 2019 11:21 am || 0

In this article, we will learn how to iterate through a loop using key, values of the dictionary. And also how to preserve the order of the dictionary.

What is an Iterator?

In Python, an iterator is an object that is used to traverse through all the elements in a collection or an array. This object has a countable amount of values. It implements the iterator protocol that has two methods namely, iter() and next().

The iter() returns the iterator object and also defined the __getitem__ method. This method is also used for the initialization of the iterator object. The next() method is used to return the next element from the sequence of elements.

The iterator has next() method in Python 2 and __next__ method in Python 3. When the iterator is used on a for loop, then the next() method is called on the object. The iterator raises a StopIteration to signal the end of an iteration.

Iterating through Dictionary in Python

Dictionaries in Python are used to store key-value pairs in an unordered manner. There are basically three ways to iterate through a dictionary:

  1. Iterating over the key-value pairs.
  2. Iterating over the keys in the dictionary.
  3. Iterating over the values in the dictionary.

1) Iterating Over the Key-Value Pairs

In this example, we iterate the dictionary using “for” loop and getting each ‘key value pair’ by using items() function as output.

Example 1

# Python3
# Iterating over dictionary with key-value pairs.

# Initialized a dictionary
fruitscolor = {"Banana" : "Yellow",
"Mango" : "Green",
"Apple" : "Red",
"Grapefruit" : "Pink",
"Blackberry" : "Purple",
"Sapodilla" : "Brown"}

# For loop to Iterating over key & value
for fruit, color in fruitscolor.items():
 print(fruit, ":", color)

Output

Banana : Yellow
Mango : Green
Apple : Red
Grapefruit : Pink
Blackberry : Purple
Sapodilla : Brown

Explanation

In the above example, we initialized a dictionary with name “fruitscolor”. This dictionary contains the name of fruit as ‘key’ and their respective color as ‘values’. Then we used a for loop with two variables fruitcolor to iterate through the keys and value of dictionary respectively.

Example 2

# Python3
# Iterating over dictionary with key-value pairs.

# Initialized a dictionary
fruitscolor = {"Banana" : "Yellow",
"Mango" : "Green",
"Apple" : "Red",
"Grapefruit" : "Pink",
"Blackberry" : "Purple",
"Sapodilla" : "Brown"}

# For loop to Iterating over key & value
for fruit in fruitscolor:
 print("{} = {}". format(fruit, fruitscolor[fruit]))

Output

Banana = Yellow
Mango = Green
Apple = Red
Grapefruit = Pink
Blackberry = Purple
Sapodilla = Brown

Explanation

In the above example, for loop is defined to iterate over keys of dictionary named ‘fruitscolor'. For each loop move it implicitly/ automatically pickup the value of loop key from the dictionary and so on.

2) Iterating Over the Keys in the Dictionary

In this example, we iterate through a dictionary using “for” loop and as output, we are getting each key value.

Example

# Python3
# Iterating over dictionary with key.

# Initialized a dictionary
fruitscolor = {"Banana" : "Yellow",
"Mango" : "Green",
"Apple" : "Red",
"Grapefruit" : "Pink",
"Blackberry" : "Purple",
"Sapodilla" : "Brown"}

# For loop to Iterating over key
for key in fruitscolor:
 print (key)

Output

Banana
Mango
Apple
Grapefruit
Blackberry
Sapodilla

3) Iterating Over the Values in the Dictionary

Here we are using “for loop” to put each item in the dictionary and getting the value of item by using value() function as output.

Example

# Python3
# Iterating over dictionary with value.

# Initialized a dictionary
fruitscolor = {"Banana" : "Yellow",
"Mango" : "Green",
"Apple" : "Red",
"Grapefruit" : "Pink",
"Blackberry" : "Purple",
"Sapodilla" : "Brown"}

# Using for loop Iterating over item and get value of item through value() function
for color in fruitscolor.values():
 print(color)

Output

Yellow
Green
Red
Pink
Purple
Brown

Explanation

In the above example, we used values() a built-in method. This values() method returns a list of all values in a dictionary. Thus we used a for loop with values() method for iterating over the values of the dictionary. Hence, the output only contains values and not the keys.

Preserve the order of keys and values in a dictionary

As we know that dictionary is the collection of un-ordered data so the order of key and value pair can be changed every time when we run the code, to maintain the order of key-value pair in the dictionary we use OrderedDict() function.

Example

# Python3
# Iterating over dictionary with key-value pairs
# OrderedDict to print dictionary in a specific order

from collections import OrderedDict

# Initialized a dictionary
fruitscolor = {"Banana" : "Yellow",
"Mango" : "Green",
"Apple" : "Red",
"Grapefruit" : "Pink",
"Blackberry" : "Purple",
"Sapodilla" : "Brown"}

# Get order of dictionary
fruitscolor = OrderedDict(fruitscolor)

# For loop to Iterating with key & value
for fruit, color in fruitscolor.items():
 print(fruit, ":", color)

Output

Banana : Yellow
Mango : Green
Apple : Red
Grapefruit : Pink
Blackberry : Purple
Sapodilla : Brown

Explanation

In the above example, we used a built-in method OrderedDict() which helps in maintaining the original order of keys and value of a dictionary.