Python enumerate dictionary | Example code

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.

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)


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)


Python enumerate dictionary

Do comment if you have any doubts and suggestions on this Python enumerate topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.