How to Iterate over dictionaries using ‘for’ loop in Python
In this text, we will see different ways to iterate over dictionaries with the help of a ‘for’ loop in Python. There are several ways of iterating over dictionaries with for loops in Python and in this text, we are going to discuss all of them with suitable examples. So, read this text to learn the concepts of iterating over dictionaries with for loops.
# create a dictionary depicting marks in different subjects Marks_subjects={'Maths':98,'English':88,'Hindi':84,'Science':100,'Social Science':87} # print the dictionary print(Marks_subjects)
Output:
{'Maths': 98, 'English': 88, 'Hindi': 84, 'Science': 100, 'Social Science': 87}
This is a very simple way of printing the keys and values of a dictionary. The dictionary is printed as it is in the output section of our Python compiler. To make our output look more presentable and nice we use for loop.
For loop using keys and values:
This is one of the methods of iterating over dictionaries with for loop. In this method, we use keys and values in a for loop to iterate over a dictionary. The program is given below.
# create a dictionary depicting marks in different subjects Marks_subjects={'Maths':98,'English':88,'Hindi':84,'Science':100,'Social Science':87} # for loop using keys and values for key,value in Marks_subjects.items(): print(key,":",value)
Output:
Leave a Reply