iterate through dictionary python

Previous
Next

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.

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

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

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.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog