159

I know we use enumerate for iterating a list but I tried it on 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, key in enumerate(enumm):
    print(i, key)

OUTPUT:

0 0

1 1

2 2

3 4

4 5

5 6

6 7

Can someone please explain the output?

1
  • 5
    for i, j in enumerate(enumm) gets i incremented at every iteration, and j catches the usual item from the enumerate function argument, which in this case is a dictionary. Iterating over dicts is essentially iterating over its keys. Mar 16, 2019 at 10:01

11 Answers 11

256

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
3
  • 8
    (+1) You could also simply use dictionary.items() (without enumerate) to get a view object with key-value pairs as a list of tuples. Jul 31, 2020 at 17:47
  • 1
    I'm not sure why this is the highest rated answer. It's basically too much code; and potentially yields the wrong answer. Using enumerate with a dict is potentially dangerous. Python does not guarantee key order when using enumerate; it is potentially possible for keys to be emitted in a different order on subsequent runs. @roadrunner66's answer is the most correct solution.
    – Jim
    Aug 23, 2021 at 20:13
  • 2
    This be ok for Python 3.7+ since dictionaries are guaranteed ordered
    – Tom2shoes
    Sep 6, 2021 at 16:02
78

The first column of output is the index of each item in enumm and the second one is its keys. If you want to iterate your dictionary then use .items():

for k, v in enumm.items():
    print(k, v)

And the output should look like:

0 1
1 2
2 3
4 4 
5 5
6 6
7 7
69

Just thought I'd add, if you'd like to enumerate over the index, key, and values of a dictionary, your for loop should look like this:

for index, (key, value) in enumerate(your_dict.items()):
    print(index, key, value)
2
  • 7
    This question is related to issues about syntax, and this answer provided the shortest solution of two added parentheses: idx, (k, v) in enumerate(d.items()): Nov 4, 2019 at 0:04
  • 2
    Hi Sean, I'm not sure if you're agreeing with the answer or simply saying that shorter variables names make for a better answer? Sep 22, 2020 at 12:36
42
dict1={'a':1, 'b':'banana'}

To list the dictionary in Python 2.x:

for k,v in dict1.iteritems():
        print k,v 

In Python 3.x use:

for k,v in dict1.items():
        print(k,v)
# a 1
# b banana

Finally, as others have indicated, if you want a running index, you can have that too:

for i  in enumerate(dict1.items()):
   print(i)  

 # (0, ('a', 1))
 # (1, ('b', 'banana'))

But this defeats the purpose of a dictionary (map, associative array) , which is an efficient data structure for telephone-book-style look-up. Dictionary ordering could be incidental to the implementation and should not be relied upon. If you need the order, use OrderedDict instead.

5
  • 2
    It's not letting me do a 2 character edit on this post, but the OP tagged this as being for Python 3, so the print statement needs to have parenthesis around k,v. Mar 27, 2016 at 6:17
  • @Mr. Me, ty, will fix. Mar 27, 2016 at 18:33
  • 19
    This should be noted is only available for python2. dict.iteritems() was removed in python3, see also stackoverflow.com/questions/30418481/…
    – gyger
    Jun 16, 2017 at 9:26
  • 1
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    – lkahtz
    Aug 5, 2020 at 8:19
  • Ty. Updated python3 vs python2. Added comment on enumerate. Aug 6, 2020 at 17:07
6

enumerate() when working on list actually gives the index and the value of the items inside the list. For example:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i, j in enumerate(list):
    print(i, j)

gives

0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9

where the first column denotes the index of the item and 2nd column denotes the items itself.

In a dictionary

enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, j in enumerate(enumm):
    print(i, j)

it gives the output

0 0
1 1
2 2
3 4
4 5
5 6
6 7

where the first column gives the index of the key:value pairs and the second column denotes the keys of the dictionary enumm.

So if you want the first column to be the keys and second columns as values, better try out dict.iteritems()(Python 2) or dict.items() (Python 3)

for i, j in enumm.items():
    print(i, j)

output

0 1
1 2
2 3
4 4
5 5
6 6
7 7

Voila

2
  • 1
    This is not true for dictionaries. Your code will iterate over the dictionary using an index (for the iteration) but not giving the key-value combinations of the dictionary. Use dict.items() instead.
    – Matthias
    Mar 27, 2018 at 12:35
  • yes you can also go ahead with dict.items(). Thanks for the correction. Mar 28, 2018 at 6:52
6

Since you are using enumerate hence your i is actually the index of the key rather than the key itself.

So, you are getting 3 in the first column of the row 3 4even though there is no key 3.

enumerate iterates through a data structure(be it list or a dictionary) while also providing the current iteration number.

Hence, the columns here are the iteration number followed by the key in dictionary enum

Others Solutions have already shown how to iterate over key and value pair so I won't repeat the same in mine.

4
  1. Iterating over a Python dict means to iterate over its keys exactly the same way as with dict.keys()
  2. The order of the keys is determined by the implementation code and you cannot expect some specific order:

    Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.

That's why you see the indices 0 to 7 in the first column. They are produced by enumerate and are always in the correct order. Further you see the dict's keys 0 to 7 in the second column. They are not sorted.

3

That sure must seem confusing. So this is what is going on. The first value of enumerate (in this case i) returns the next index value starting at 0 so 0, 1, 2, 3, ... It will always return these numbers regardless of what is in the dictionary. The second value of enumerate (in this case j) is returning the values in your dictionary/enumm (we call it a dictionary in Python). What you really want to do is what roadrunner66 responded with.

3

Python3:

One solution:

enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, k in enumerate(enumm):
    print("{}) d.key={}, d.value={}".format(i, k, enumm[k]))

Output:
0) enumm.key=0, enumm.value=1
1) enumm.key=1, enumm.value=2
2) enumm.key=2, enumm.value=3
3) enumm.key=4, enumm.value=4
4) enumm.key=5, enumm.value=5
5) enumm.key=6, enumm.value=6
6) enumm.key=7, enumm.value=7

An another example:

d = {1 : {'a': 1, 'b' : 2, 'c' : 3},
     2 : {'a': 10, 'b' : 20, 'c' : 30}
    }    
for i, k in enumerate(d):
        print("{}) key={}, value={}".format(i, k, d[k])

Output:    
    0) key=1, value={'a': 1, 'b': 2, 'c': 3}
    1) key=2, value={'a': 10, 'b': 20, 'c': 30}
3

You may find it useful to include index inside key:

d = {'a': 1, 'b': 2}
d = {(i, k): v for i, (k, v) in enumerate(d.items())}

Output:

{(0, 'a'): True, (1, 'b'): False}
1
d = {0: 'zero', '0': 'ZERO', 1: 'one', '1': 'ONE'}

print("List of enumerated d= ", list(enumerate(d.items())))

output:

List of enumerated d=  [(0, (0, 'zero')), (1, ('0', 'ZERO')), (2, (1, 'one')), (3, ('1', 'ONE'))]

Not the answer you're looking for? Browse other questions tagged or ask your own question.