How to enumerate dictionary in Python?

Following is the help on how to enumerate dictionary in Python.

how to enumerate dictionary in Python

Let’s say this is my dictionary:

my_dictionary = {'Audi' : 1000, 'BMW' : 2000, 'Mercedes' : 3000}

Enumerating a dictionary

This is how to enumerate the dictionary in Python:

my_dictionary = {'Audi' : 1000, 'BMW' : 2000, 'Mercedes' : 3000}
for i, (car, number) in enumerate(my_dictionary.items()):
    print("index: {}, car: {}, number: {}".format(i, car, number))

In this code, the enumerate function is used to assign an index (i) and unpack each key-value pair (as car and number) from my_dictionary.items. We then print the index, car brand, and the corresponding number for each item in the dictionary.

See also  Exploring Metaclasses in Python

how to enumerate dictionary in Python

By enumerating the dictionary, you can efficiently access and process its key-value pairs, making it a valuable tool for various data manipulation and analysis tasks in Python.