Enumerate Dictionary In Python: Video Demonstration

Previously I looked at how to use the enumerate() built-in function with a for loop to provide two variables when iterating through a list . In that article the enumerate() function provides both an index number and the element in each list by wrapping these together into a tuple.

But what happens when the enumerate() function is applied to a dictionary?

As done previously let’s inspect the output of the enumerated dictionary by printing its contents:

>>> my_dict = {'a': 100, 'b': 200, 'c': 300}
>>> list(enumerate(my_dict))
[(0, 'a'), (1, 'b'), (2, 'c')]

From the above output, you can easily conclude that the enumerate function exposes the key value of each element within a dictionary.

Knowing this would help if you wanted to loop through the dictionary using a for-loop.

By applying the same principle taught in the previous article on using a for loop with two variables you would define the first variable as the index and the second item as the key to the dictionary, like so:

>>> my_dict = {'a': 100, 'b': 200, 'c': 300}
>>> for idx, key in enumerate(my_dict):
...     print(idx, key, my_dict[key])
...
0 a 100
1 b 200
2 c 300

As you can see from the output above the enumerate function provides access to a tuple containing the index number and the key, should these both be needed when looping through your dictionary.

The equivalent of using the enumerate function would be to define your index variable outside the for loop and to increment the variable through each iteration of the dictionary’s keys, like so:

>>> my_dict = {'a': 100, 'b': 200, 'c': 300}
>>> idx = 0
>>> for key in my_dict:
...     print(idx, key, my_dict[key])
...     idx += 1
...
0 a 100
1 b 200
2 c 300

The idx += 1 part in the code above representing the way to increment in Python the variable idx by one each time the for loop passes through a key in the dictionary.

Summary

The enumerate function can be used on a dictionary in Python and when combined with the two-variable for loop can provide a way to access an index number as well as the key when iterating through a Python dictionary.

Find out if this method helps with sorting a list of dictionaries here .

Photo of author
Ryan Sheehy
Ryan has been dabbling in code since the late '90s when he cut his teeth exploring VBA in Excel. Having his eyes opened with the potential of automating repetitive tasks, he expanded to Python and then moved over to scripting languages such as HTML, CSS, Javascript and PHP.