Python – Enumerate a Dictionary

Enumerate a Dictionary in Python

In Python, enumerate() takes a dictionary as argument and adds a counter value to the dictionary iterable.

In a For Loop, we can access the index of the (key: value) pair along with the (key: value) pair itself.

Examples

1. Enumerate the keys in given dictionary

In this example, we will take a dictionary, and enumerate over the keys of dictionary in a For Loop.

Python Program

fruits = {'apple': 25, 'banana': 14, 'mango':48, 'cherry': 30}
for x in enumerate(fruits):
    print(x)
Run Code Copy

Output

(0, 'apple')
(1, 'banana')
(2, 'mango')
(3, 'cherry')

2. Enumerate the values in given dictionary

In this example, we will take a dictionary, and enumerate over the values of dictionary in a For Loop.

Python Program

fruits = {'apple': 25, 'banana': 14, 'mango':48, 'cherry': 30}
for x in enumerate(fruits.values()):
    print(x)
Run Code Copy

Output

(0, 25)
(1, 14)
(2, 48)
(3, 30)

3. Enumerate the Key:Value pairs in given Dictionary

In this example, we will take a dictionary, and enumerate over the key:value pairs of dictionary in a For Loop.

Python Program

fruits = {'apple': 25, 'banana': 14, 'mango':48, 'cherry': 30}
for x in enumerate(fruits.items()):
    print(x)
Run Code Copy

Output

(0, ('apple', 25))
(1, ('banana', 14))
(2, ('mango', 48))
(3, ('cherry', 30))

Summary

In this tutorial of Python Examples, we learned how to enumerate a dictionary using enumerate() builtin function.

Code copied to clipboard successfully 👍