Search code examples
pythondictionaryhashenumerate

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

Solution

  • 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