user3079275 user3079275 - 1 year ago 107
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download