Following is the help on 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))
Enumerate is returning the tuple object and my_dictionary.items returns an iterator. To gether they are returning both an index and a tuple of a pair key and value.
Key Takeaways
- To enumerate a dictionary in Python, you can use the `enumerate()` function.
- The `enumerate()` function returns an iterator that yields a tuple of two elements: the index of the element in the dictionary and the value of the element.
- You can use the `enumerate()` function to iterate over a dictionary and print the index and value of each element.
FAQ
- Q: What is the difference between `enumerate()` and `items()`?
- A: The `enumerate()` function returns an iterator that yields a tuple of two elements: the index of the element in the dictionary and the value of the element. The `items()` function returns an iterator that yields tuples of two elements: the key and the value of each element in the dictionary.
- Q: What is the advantage of using `enumerate()`?
- A: The advantage of using `enumerate()` is that it allows you to access the index of the element in the dictionary. This can be useful if you need to know the order in which the elements were added to the dictionary.