VOOZH about

URL: https://www.geeksforgeeks.org/python/get-index-of-values-in-python-dictionary/

⇱ Get Index of Values in Python Dictionary - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Get Index of Values in Python Dictionary

Last Updated : 23 Jul, 2025

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 when those values are stored in a list. For example, consider the following dictionary: a = {1: [1, 2], 2: [3, 4, 6]} here for each list stored as a value we want to retrieve the indices of its elements then the expected output for the example above is: [[0, 1], [0, 1, 2]]

Using Enumerate and List Comprehension

This is the simplest and most efficient way in which the built-in enumerate() function lets us loop over a list while keeping track of each element’s index. We can combine enumerate() with list comprehension to generate the index lists for all dictionary values.


Output
[[0, 1], [0, 1, 2]]

Explanation:

  • We loop over every list (value) in the dictionary using a.values() and for each list x, we use enumerate(x) to obtain a pair of index i and its corresponding value val.
  • list comprehension collects the index i for every element in x

Using Dictionary Comprehension

In this method we use dictionary comprehension along with enumerate() to create a new dictionary that maps each original key to its list of indices.


Output
{1: [0, 1], 2: [0, 1, 2]}

Explanation:

  • dictionary comprehension iterates over each key-value pair using a.items() and for each key the corresponding value (which is a list) is processed with enumerate() to extract its indices.
  • This creates a new dictionary where each key is associated with a list of indices for its value.

Using a Simple Loop

If you prefer using loops for clarity a regular loop can also achieve the same result, this method builds the index lists step by step.


Output
[[0, 1], [0, 1, 2]]

Explanation:

  • The code iterates through each list (the values of the dictionary) and, for each list, it creates a new list of indices corresponding to the positions of the elements (using range(len(x))).
  • Each list of indices is appended to the result list res and finally the complete list of indices for all dictionary values is printed.
Comment