[python] enumerate() for dictionary in python

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

OUTPUT:

0 0

1 1

2 2

3 4

4 5

5 6

6 7

Can someone explain the output?

This question is related to python python-3.x dictionary enumerate

The answer is


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)

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.


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'))]

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

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


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}

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

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.


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}

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.


  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.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to enumerate

enumerate() for dictionary in python How to enumerate an enum with String type? What does enumerate() mean? Objective-C: Reading a file line by line