Iterating through a Dictionary in Python
In this tutorial, we will see various ways to iterate through a Dictionary in Python
We will see how to iterate through the elements of a dictionary in Python using
items()
method available on dictionaryenumerate()
method in Python to iterate through the elements of dictionary
Iterate a dictionary using items() method
The dictionary in Python exposes a method items()
which is of type dict_items
. Each item is a tuple representing a key and value.
In the preceding code, we see that the for
loop is capturing the key and value for each iteration of dict items, using the variables, k and v respectively.
The output will be as follows.
Iterate through the keys of dictionary using enumerate()
To iterate over the keys of dictionary along with index of iteration, you can use enumerate()
method. The following example demonstrates the way of iterating through the keys of dictionary using enumerate()
in Python.
In the preceding code, we see the iteration variable i is used to represent the value held in each iteration. The following are the properties of i in this for
loop demonstrated in this example.
- The type of i in this case will be a
tuple
. - The value of i for each iteration will hold the index of iteration and the dictionary key.
The output will be as follows.
Method 1: Iterate through the keys and values of dictionary using enumerate() and dict.items() in Python
To iterate over both the keys and values of dictionary along with index of iteration, you can use still use enumerate()
method along with items()
method. The following example demonstrates the way of iterating through the keys and values of dictionary along with index using enumerate()
and items()
in Python.
In the preceding code, we see the iteration variable idx is used to represent the index of each iteration. The tuple t represents the key value pair. The following are the properties of idx and t in this for
loop demonstrated in this example.
- The type of idx is of type
int
. - The value of idx for each iteration will hold the index of iteration
- The type of t is of type
tuple
. - The value held by t for each iteration will be the tuple representation of key and value for each iteration of dict items.
The output will be as follows.
Method 2: Iterate through the keys and values of dictionary using enumerate() and dict.items() in Python
To iterate over both the keys and values of dictionary along with index of iteration, you can use still use enumerate()
method along with items()
method. In this approach, we will directly unpack the idx, key and value of a dictionary.
The following example demonstrates the way of iterating through the keys and values of dictionary along with index using enumerate()
and items()
in Python.
The output will be as follows.