VOOZH about

URL: https://www.geeksforgeeks.org/python/python-dictionary-with-index-as-value/

⇱ Python - Dictionary with Index as Value - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.


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.


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.


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.
Comment