Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

iterate through dictionary 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.

The post iterate through dictionary python appeared first on Java2Blog.



This post first appeared on How To Learn Java Programming, please read the originial post: here

Share the post

iterate through dictionary python

×

Subscribe to How To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×