Iterate through dictionary in python

In this post, we will see how to iterate through dictionary in python.
You can use for key in dict.keys(): to iterate over keys of dictionary.

for key in dict.keys():
     print(key)

You can use for value in dict.values(): to iterate over values of dictionary.

for key in dict.values():
     print(key)

You can use items() method to iterate over key-value pairs of dictionary.

for key,value in dict.items():
     print(key,":",value)

Let’s understand with the help of example.

dict1={1:"one",2:"two",3:"three"}
print("Dictionary:",dict1)

print("================")
print("Printing keys:")
print("================")

for key in dict1.keys():
    print(key)

print("================")
print("Printing values:")
print("================")

for value in dict1.values():
    print(value)

print("============================")
print("Printing key-value pairs:")
print("============================")

for key,value in dict1.items():
    print(key,":",value)

Output:

Dictionary: {1: ‘one’, 2: ‘two’, 3: ‘three’}
================
Printing keys:
================
1
2
3
================
Printing values:
================
one
two
three
============================
Printing key-value pairs:
============================
1 : one
2 : two
3 : three

That’s all about iterating over dictionary in Python.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.