user3079275 user3079275 - 1 month ago 5
Python Question

Enumerating through a dictionary in Python

I am trying to enumerate through a dictionary like this but it does not work. What's the simplest way to iterate through a dictionary in python while enumerating each entry?

for i, k, v in enumerate(my_dict.iteritems()):
print i, k, v

Answer

You just need to add parenthesis around (k, v) tuple:

>>> d = {1: 'foo', 2: 'bar'}
>>> for i, (k, v) in enumerate(d.iteritems()):
...     print i, k, v
...
0 1 foo
1 2 bar
Comments