![]() |
VOOZH | about |
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]]
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.
[[0, 1], [0, 1, 2]]
Explanation:
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.
{1: [0, 1], 2: [0, 1, 2]}
Explanation:
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.
[[0, 1], [0, 1, 2]]
Explanation: