I have a list of pairs of integers [(int1, int2), (int3, int4) …], (or any immutable objects that can be used as dict keys).
I want a dict where each element is a unique element of the input list, and each value is a list of indices of the element in the list.
eg
l = [(1,2),(1,2),(1,3),(1,4),(5,2)]
d = {(1, 2): [0, 1], (1, 3): [2], (1, 4): [3], (5, 2): [4]}
I can build this dictionary in the following way
def indices_dict(l):
d = {}
for i, e in enumerate(l):
if not e in d:
d[e] = []
d[e].append(i)
return dict(d)
But I seems like looping over all the elements if not optimal.
How could I make this faster by using more builtin python or numpy functions ?
1