Open In App

Iterate Python Dictionary Using Enumerate() Function

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python dictionaries are versatile data structures used to store key-value pairs. When it comes to iterating through the elements of a dictionary, developers often turn to the enumerate() function for its simplicity and efficiency. In this article, we will explore how to iterate through Python dictionaries using the enumerate() function and provide three commonly used examples with accompanying code snippets.

Iterate Python Dictionary Using Enumerate() Function

Below, are the methods for Iterate Python Dictionary Using Enumerate() Function in Python.

Example 1: Basic Iteration with Enumerate()

In this example, the enumerate() function is used with the items() method of the dictionary, which returns key-value pairs. The loop unpacks each pair into variables key and value, while index keeps track of the iteration index. This allows for easy access to both the key and value along with their corresponding index.

Python3




# Sample dictionary
sample_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
 
# Iterating using enumerate()
for index, (key, value) in enumerate(sample_dict.items()):
    print(f"Index: {index}, Key: {key}, Value: {value}")


Output

Index: 0, Key: a, Value: 1
Index: 1, Key: b, Value: 2
Index: 2, Key: c, Value: 3
Index: 3, Key: d, Value: 4

Example 2: Enumerating with a Custom Start Index

In this example, the enumerate() function accepts an additional argument, start, which determines the starting value of the index. By setting start=1, we begin indexing from 1 instead of the default 0. This is particularly useful when presenting results to users or when indexing starts at 1 in a specific context.

Python3




# Sample dictionary
grades = {'Alice': 90, 'Bob': 85, 'Charlie': 92, 'David': 78}
 
# Iterating with a custom start index
for position, (student, score) in enumerate(grades.items(), start=1):
    print(f"Position: {position}, Student: {student}, Score: {score}")


Output

Position: 1, Student: Alice, Score: 90
Position: 2, Student: Bob, Score: 85
Position: 3, Student: Charlie, Score: 92
Position: 4, Student: David, Score: 78

Example 3 : Filtering Dictionary Elements During Iteration

In this example, a generator expression is used within the enumerate() function to filter dictionary elements based on a condition. In this case, only cities with a population greater than 3 million are included in the iteration. This showcases how enumerate() can be combined with other Python features to perform more complex operations during iteration.

Python3




# Sample dictionary
population = {'New York': 8398748, 'Los Angeles': 3980400, 'Chicago': 2716000, 'Houston': 2328000}
 
# Iterating and filtering elements based on population
for city, pop in enumerate((city, pop) for city, pop in population.items() if pop > 3000000):
    print(f"City: {city}, Population: {pop}")


Output

City: 0, Population: ('New York', 8398748)
City: 1, Population: ('Los Angeles', 3980400)

Conclusion

The enumerate() function is a powerful tool for iterating through Python dictionaries, providing a concise and readable way to access both the key-value pairs and their corresponding indices. By exploring these three examples, developers can enhance their understanding of how to leverage enumerate() for various scenarios, from basic iteration to customizing index starts and filtering elements based on specific criteria.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads