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.
1 2 3 4 |
for key in dict.keys(): print(key) |
You can use for value in dict.values(): to iterate over values of dictionary.
1 2 3 4 |
for key in dict.values(): print(key) |
You can use items() method to iterate over key-value pairs of dictionary.
1 2 3 4 |
for key,value in dict.items(): print(key,":",value) |
Let’s understand with the help of example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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
================
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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.