enumerate() for dictionary in Python

enumerate() for dictionary in Python

On top of the already provided answers there is a very nice pattern in Python that allows you to enumerate both keys and values of a dictionary.

The normal case you enumerate the keys of the dictionary:

example_dict = {1:a, 2:b, 3:c, 4:d}

for i, k in enumerate(example_dict):
    print(i, k)

Which outputs:

0 1
1 2
2 3
3 4

But if you want to enumerate through both keys and values this is the way:

for i, (k, v) in enumerate(example_dict.items()):
    print(i, k, v)

Which outputs:

0 1 a
1 2 b
2 3 c
3 4 d

The first column of output is the index of each item in enumm and the second one is its keys. If you want to iterate your dictionary then use .items():

for k, v in enumm.items():
    print(k, v)

And the output should look like:

0 1
1 2
2 3
4 4 
5 5
6 6
7 7

enumerate() for dictionary in Python

Just thought Id add, if youd like to enumerate over the index, key, and values of a dictionary, your for loop should look like this:

for index, (key, value) in enumerate(your_dict.items()):
    print(index, key, value)

Leave a Reply

Your email address will not be published. Required fields are marked *