Python - Index Directory of Elements

When it is required to index directory of elements in a list, list comprehension along with set operator is used. This creates a dictionary mapping each unique element to all its index positions in the list.

Syntax

{key: [index for index, value in enumerate(list) if value == key] 
 for key in set(list)}

Example

Below is a demonstration of creating an index directory ?

my_list = [81, 36, 42, 57, 68, 12, 26, 26, 38]

print("The list is :")
print(my_list)

my_result = {key: [index for index, value in enumerate(my_list) if value == key]
             for key in set(my_list)}

print("The result is :")
print(my_result)
The list is :
[81, 36, 42, 57, 68, 12, 26, 26, 38]
The result is :
{36: [1], 68: [4], 38: [8], 42: [2], 12: [5], 81: [0], 57: [3], 26: [6, 7]}

How It Works

  • set(my_list) creates unique elements: {81, 36, 42, 57, 68, 12, 26, 38}

  • enumerate(my_list) provides (index, value) pairs for iteration

  • List comprehension finds all indices where value == key

  • Dictionary comprehension maps each unique element to its index list

Practical Example

Finding positions of specific grades in a student list ?

grades = ['A', 'B', 'A', 'C', 'B', 'A', 'D']

grade_positions = {grade: [i for i, g in enumerate(grades) if g == grade]
                   for grade in set(grades)}

print("Grade positions:")
for grade, positions in sorted(grade_positions.items()):
    print(f"Grade {grade}: positions {positions}")
Grade positions:
Grade A: positions [0, 2, 5]
Grade B: positions [1, 4]
Grade C: positions [3]
Grade D: positions [6]

Alternative Using defaultdict

For large lists, using defaultdict might be more efficient ?

from collections import defaultdict

my_list = [81, 36, 42, 57, 68, 12, 26, 26, 38]

index_dict = defaultdict(list)
for index, value in enumerate(my_list):
    index_dict[value].append(index)

print("Using defaultdict:")
print(dict(index_dict))
Using defaultdict:
{81: [0], 36: [1], 42: [2], 57: [3], 68: [4], 12: [5], 26: [6, 7], 38: [8]}

Conclusion

Dictionary comprehension with set() and enumerate() efficiently creates an index directory. For large datasets, consider using defaultdict for better performance as it requires only one pass through the list.

Updated on: 2026-03-26T02:08:35+05:30

313 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements