Iterate Python Dictionary Using Enumerate() Function
Last Updated :
12 Feb, 2024
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}")
OutputIndex: 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}")
OutputPosition: 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}")
OutputCity: 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.
Similar Reads
Python - Iterate over Tuples in Dictionary
In this article, we will discuss how to Iterate over Tuples in Dictionary in Python. Method 1: Using index We can get the particular tuples by using an index: Syntax: dictionary_name[index] To iterate the entire tuple values in a particular index for i in range(0, len(dictionary_name[index])): print
2 min read
Iterate Through Specific Keys in a Dictionary in Python
Sometimes we need to iterate through only specific keys in a dictionary rather than going through all of them. We can use various methods to iterate through specific keys in a dictionary in Python. Using dict.get() MethodWhen we're not sure whether a key exists in the dictionary and don't want to ra
3 min read
Python - Dictionary List Values Frequency
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the task of computing frequency of all the values in dictionary values lists. This is quite common problem and can have use cases in many domains. Let's discuss certain ways in which this task can be
6 min read
Python - Extract Equal Pair Dictionary
While working with a Python dictionary, we are supposed to create a new dictionary of the existing dictionary having tuple as key. We desire to create a singleton key dictionary with keys only where both elements of pair are equal. This can have applications in many domains. Let's discuss certain wa
5 min read
Create Nested Dictionary using given List - Python
The task of creating a nested dictionary in Python involves pairing the elements of a list with the key-value pairs from a dictionary. Each key from the list will map to a dictionary containing a corresponding key-value pair from the original dictionary. For example, given the dictionary a = {'Gfg':
3 min read
Python - Extracting Kth Key in Dictionary
Many times, while working with Python, we can have a situation in which we require to get the Kth key of dictionary. There can be many specific uses of it, either for checking the indexing and many more of these kind. This is useful for Python version 3.8 +, where key ordering are similar as inserti
4 min read
Python - Storing Elements Greater than K as Dictionary
Sometimes, while working with python lists, we can have a problem in which we need to extract elements greater than K. But sometimes, we don't require to store duplicacy and hence store by key value pair in dictionary. To track of number position of occurrence in dictionary. Method #1 : Using loop T
3 min read
Get Index of Values in Python Dictionary
Dictionary values are lists and we might need to determine the position (or index) of each element within those lists. Since dictionaries themselves are unordered (prior to Python 3.7) or ordered based on insertion order (in Python 3.7+), the concept of "index" applies to the valuesâspecifically whe
3 min read
Python Iterate Dictionary Key, Value
In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Difference Between Enumerate and Iterate in Python
In Python, iterating through elements in a sequence is a common task. Two commonly used methods for this purpose are enumerate and iteration using a loop. While both methods allow us to traverse through a sequence, they differ in their implementation and use cases. Difference Between Enumerate And I
3 min read