A dictionary in python is a collection of key-value pairs where each key is associated with a value.
It is required to loop over elements of a dictionary either to display them or to check if some key-value pair exists in it.
There are different ways to iterate through a dictionary and this article will outline them with examples.
[the_ad id=”651″]
Method 1: Using for loop
Iterate over a dictionary using any python loops such as a for loop. In every iteration, the loop variable will contain the key of dictionary entry.
You can also get the value corresponding to that key. Example,
# initialize dictionary
dict = {'google':'search', 'facebook':'social','youtube':'videos'}
# iterate dictionary with for loop
for key in dict:
print('Key:', key, ', Value:', dict[key])
This program will print below output
Key: google , Value: search
Key: facebook , Value: social
Key: youtube , Value: videos
dict class has an inbuilt iterator which can be used to loop over a dictionary. Use __iter__() function to get the dictionary iterator.Use a
for loop to iterate over the keys of the dictionary. Example,
# initialize dictionary
dict = {'google':'search', 'facebook':'social','youtube':'videos'}
for item in dict.__iter__():
print('Key:',item,', Value:',dict[item])
Above code produces the below output
Key: google , Value: search
Key: facebook , Value: social
Key: youtube , Value: videos
Inbuilt
items() functions returns all the items of the dictionary. Each item is a python tuple of the dictionary entry.A dictionary can be iterated using a for loop over these items. Example,
#initialize dictionary
dict = {'google':'search', 'facebook':'social','youtube':'videos'}
for item in dict.items():
print(item)
As stated before, each value returned by items() function returns a tuple. Thus, if you print the type of the value using type function as shown below
for item in dict.items():
print(type(item))
then the output is
<class ‘tuple’>
<class ‘tuple’>
<class ‘tuple’>
dict class provides an inbuilt keys() function which returns a collection of all the keys of dictionary.This method can be used to loop through dictionary by key. Example,
#initialize dictionary
dict = {'google':'search', 'facebook':'social','youtube':'videos'}
for key in dict.keys():
print('Key:', key, ', Value:', dict[key])
Above example outputs
Key: google , Value: search
Key: facebook , Value: social
Key: youtube , Value: videos
Similar to keys() function, there is a values() function which can be used to access values of a dictionary as shown below.
dict = {'google':'search', 'facebook':'social','youtube':'videos'}
for value in dict.values():
print('Value:', key)
Above example will print
Value: search
Value: social
Value: videos