How to Iterate Through All Key-Value Pairs of a Dictionary in Python



Python


In this article, we show how to iterate through all key-value pairs of a dictionary in Python.

So, say, we have a dictionary. This can be any dictionary.

A dictionary contains key-value pairs. Each key contains a value.

Let's say we have a create a dictionary that contains student names. Each key is student1, student2, student3, etc. Each value is the name of the student.

How then can we iterate through all of the key-value pairs of this dictionary, as such to print them out?

The code below shows how to do this.



So first we create a dictionary called students.

This dictionary has 3 key-value pairs.

The first key-value pair is Student1:Daniel.

The second key-value pair is Student2:Michael.

The third key-value pair is Student3:Peter

We loop through all key-value pairs in the students dictionary by using a for loop.

The items() function allows us to go each item of a dictionary.

We then print each key-value pair using the format() function.

So you can see it's just a basic for loop using the items() function to go through each item. And you must declare 2 variables representing the key and value. The first variable is the key and the second variable is the value.

And this is all that is required to iterate through all key-value pairs (items) of a dictionary in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...