Iterate Through Dictionary In Python

In this tutorial, I will show you how to iterate through dictionary in python. So without wasting any further time let’s get started.

1. Iterate Through Keys Of Dictionary

The keys() method of the python dictionary returns the iterable containing the keys of the dictionary.

In the below code example, we will use the keys() method to iterate through all the keys of the dictionary.

# below is the program to iterate through dictionary in python
dictionary = {
            "Key1":"Value1",
            "Key2":"Value2",
            "Key3":"Value3"
            }

for i in dictionary.keys():# iterate through keys
    print(i)

Here is the output of the above code.

Output :

output of program to iterate through dictionary in python

2. Iterate Through Values Of Dictionary

The values() method of the python dictionary returns the iterable containing the values of the dictionary.

In the following code snippet, we will use the values() method to iterate through all the values of the dictionary.

dictionary = {
            "Key1":"Value1",
            "Key2":"Value2",
            "Key3":"Value3"
            }

for i in dictionary.values(): # iterate through values
    print(i)

Output :

Value1
Value2
Value3

3. Iterate Through Keys,Values

In the below code example, we will use the items() method to iterate through all the keys as well as values of the dictionary.

# Program to Iterate Through Dictionary In Python
dictionary = {
            "Key1":"Value1",
            "Key2":"Value2",
            "Key3":"Value3"
            }

for key,value in dictionary.items(): # iterate through both key,value
    print(key,":",value)

Output :

Key1 : Value1
Key2 : Value2
Key3 : Value3

Also read about how to convert list to dictionary in python.

Leave a Reply