4

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
user2399453
  • 2,930
  • 5
  • 33
  • 60
  • 1
    Note that the iteration order is [arbitrary](https://docs.python.org/2/library/stdtypes.html#dict.items). Consider using [OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict) if you want to iterate in insertion order. – tom Oct 30 '16 at 01:56

1 Answers1

10

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
niemmi
  • 17,113
  • 7
  • 35
  • 42