>>> strlist = ['the', 'the', 'boy', 'happy', 'boy', 'happy']
>>> from collections import defaultdict
>>> D = defaultdict(set)
>>> for i, s in enumerate(strlist):
... D[s].add(i)
...
>>> D
defaultdict(<type 'set'>, {'boy': {2, 4}, 'the': {0, 1}, 'happy': {3, 5}})
If you can't use defaultdict
for some reason
>>> D = {}
>>> for i, s in enumerate(strlist):
... D.setdefault(s, set()).add(i)
...
>>> D
{'boy': {2, 4}, 'the': {0, 1}, 'happy': {3, 5{}
Here is the silly (inefficient) way to write it as a comprehension
>>> {k: {i for i, j in enumerate(strlist) if j == k} for k in set(strlist)}
{'boy': {2, 4}, 'the': {0, 1}, 'happy': {3, 5}}