Python - How To Enumerate Dictionary in Python

ID : 203

viewed : 195

Tags : PythonPython Dictionary

vote vote

95

The enumerate() function in Python returns an enumerate-type object and adds a counter variable to iterate over a list or some other type of collection. It makes looping over such objects easier.

We can view the contents of an enumerate object when we pass it to the list() function. For example:

l = ['a','b','c'] print(list(enumerate(l))) 

Output:

[(0, 'a'), (1, 'b'), (2, 'c')] 

We can also use the enumerate() function with dictionaries as well.

The following example shows an elementary example.

d1 = {'a' : 15,'b' : 18,'c' : 20}  for i,j in enumerate(d1):     print(i,j) 

Output:

0 a 1 b 2 c 

Notice that we directly passed the dictionary to the enumerate() function, and it only assigned the counter variable to the keys of the dictionary and not to the values. So when we iterate over this object, we could only access the counter variable and the dictionary’s keys.

To enumerate both keys and values, we can use the dictionary items() method. The items() method returns an object with the key-value pairs as tuples. The following example shows how we can use the items() method with the enumerate() function and access both the key and its corresponding value.

d1 = {'a' : 15,'b' : 18,'c' : 20}  for i, (j,k) in enumerate(d1.items()):     print(i,j,k) 

Output:

0 a 15 1 b 18 2 c 20 

If we only want the dictionary elements without their keys, we can use the values() function. It returns a list containing the dictionary values.

The following code shows how:

d1 = {'a' : 15,'b' : 18,'c' : 20}  for i,j in enumerate(d1.values()):     print(i,j) 

Output:

0 15 1 18 2 20 

  • Related HOW TO?