enumerate() for dictionary in python

Aditya Krishn picture Aditya Krishn · Mar 27, 2016 · Viewed 146.8k times · Source

I know we use enumerate for iterating a list but I tried it in a dictionary and it didn't give an error.

CODE:

enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}

for i, j in enumerate(enumm):
    print(i, j)

OUTPUT:

0 0

1 1

2 2

3 4

4 5

5 6

6 7

Can someone explain the output?

Answer

João Almeida picture João Almeida · Dec 20, 2018

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