Python - Dictionary with Index as Value
Last Updated :
11 Jul, 2025
We are having a list we need to find index of each element and store it in form of dictionary. For example, a = ['a', 'b', 'c', 'd'] we need to find index of each elements in list so that output should be {'a': 0, 'b': 1, 'c': 2, 'd': 3}.
Using Dictionary Comprehension
We can use dictionary comprehension to create a dictionary where each element of a list is mapped to its index. This is achieved by enumerating the list and constructing key-value pairs with elements as keys and their indices as values.
Python
a = ['a', 'b', 'c', 'd']
# Create a dictionary with elements as keys and their indices as values
ind = {val: idx for idx, val in enumerate(a)}
print(ind)
Output{'a': 0, 'b': 1, 'c': 2, 'd': 3}
Explanation:
enumerate(a) generates index-value pairs from list which are used in dictionary comprehension to create key-value pairs.- Resulting dictionary maps each element of the list to its corresponding index providing an efficient way to track positions.
Using a Loop
We can use a for loop with enumerate() to iterate over the list and store each element as a key with its index as value in a dictionary. This approach builds dictionary step by step without using comprehension.
Python
a = ['a', 'b', 'c', 'd']
ind = {}
# Iterate over the list with index-value pairs
for idx, val in enumerate(a):
# Assign the element as the key and its index as the value
ind[val] = idx
print(ind)
Output{'a': 0, 'b': 1, 'c': 2, 'd': 3}
Explanation:
- For loop iterates through the list using enumerate() extracting both index and element.
- Each element is stored as a key in dictionary with its corresponding index as value.
Using dict() with zip()
We can use dict(zip(lst, range(len(lst)))) to create a dictionary where each element of list is mapped to its index. zip() function pairs elements with their indices and dict() converts these pairs into a dictionary.
Python
a = ['a', 'b', 'c', 'd']
# Use zip() to pair elements with their indices and convert to a dictionary
ind = dict(zip(a, range(len(a))))
print(ind)
Output{'a': 0, 'b': 1, 'c': 2, 'd': 3}
Explanation:
- zip(a, range(len(a))) pairs each element in the list with its corresponding index.
- dict() converts these key-value pairs into a dictionary mapping each element to its index efficiently.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice