Write A Python Script To Traverse A Dictionary

In this article let's learn how to traverse / iterate over the items of the dictionary. Given a dictionary you can list both key value pairs together, you can also get only the keys or only values.

I will be using the built in dictionary functions to traverse a dictionary.

 

Write A Python Script To Traverse A Dictionary

 

 

Write A Python Script To Traverse A Dictionary

Let's take a dictionary named as fruits and declare some values inside the program. The keys and value pairs of the dictionary include fruit name and cost of each fruit. As shown below.


fruits = {"apple" : 120, "banana": 30, "grapes": 50, "orange": 90}





Now in order to iterate the key value pair of the dictionary use the built in function items() to get the key value pair to gather.

for key, value in fruits.items():
   print(f"Fruit {key} costs : {value}")




To list out only keys present in the dictionary user keys() function as shown below

print("\nList of fruits are ...")
for key in fruits.keys():
   print(key)





For listing out the values there are two options
    First is user values() function call
     Second is the user dictionary[keys] to get the values displayed.

print("\nList of dictionary values are ...")
for value in fruits.values():
   print(value)
 
print("\nList of dictionary values are ...")
for key in fruits.keys():
   print(fruits[key])




Python Code
=====================

fruits = {"apple" : 120, "banana": 30, "grapes": 50, "orange": 90}

for key, value in fruits.items():
   print(f"Fruit {key} costs : {value}")


print("\nList of fruits are ...")
for key in fruits.keys():
   print(key)

print("\nList of dictionary values are ...")
for value in fruits.values():
   print(value)
 
print("\nList of dictionary values are ...")
for key in fruits.keys():
   print(fruits[key])






Output
================
Fruit apple costs : 120
Fruit banana costs : 30
Fruit grapes costs : 50
Fruit orange costs : 90

List of fruits are ...
apple
banana
grapes
orange

List of dictionary values are ...
120
30
50
90

List of dictionary values are ...
120
30
50
90





Conclusion
====================
Change the dictionary items from fruits to student name vs marks scored in a given year, then try printing out the key, value pairs by traversing all the items present in the dictionary.

Comment it down below if you have any suggestions to improve the above python program.






Post a Comment

0 Comments