Enumerate Dictionary in Python

Enumerate Dictionary in Python

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
Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python Dictionary

  • Check if a Key Exists in a Dictionary in Python
  • Convert a Dictionary to a List in Python
  • Get All the Files of a Directory
  • Find Maximum Value in Python Dictionary
  • Delete a File and Directory in Python
  • Sort a Python Dictionary by Value