Python allows you to enumerate both keys and values of a dictionary. In the normal case, you enumerate the keys of the dictionary but in this tutorial, you will get examples of how to enumerate through both keys and values.
the enumerate()
function returns an iterator that yields tuples containing the index and the key-value pair of each item in the dictionary
Enumerate dictionary example
Simple example code Iterate over dictionary using enumerate() function in Python.
You will get keys in this method.
example_dict = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
for i, k in enumerate(example_dict):
print(i, k)
Output:
0 1
1 2
2 3
3 4
But if you want to enumerate through both keys and values this is the way:
example_dict = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
for i, (k, v) in enumerate(example_dict.items()):
print(i, k, v)
Output:
Do comment if you have any doubts or suggestions on this Python enumerate topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.