Dev Helpers
← Back

Collect repeated labels without losing their positions

Collect repeated labels without losing their positions using Python lists and dictionaries.

Open this example in the interactive library

Source code

from collections import defaultdict
slots = defaultdict(list)
for index, label in enumerate(['red', 'blue', 'red']):
    slots[label].append(index)
print(dict(slots))

Sample output

{'red': [0, 2], 'blue': [1]}