Ferenc Bodon
Ferenc Bodon

Reputation: 452

indices of all occurrences of all elements

given a list I would like to see indices of all occurrences of all elements in a dictionary. I am looking for the Python implementation of function group offered by the Q programming language. I am expecting a simpler solution than code below

l=[2, 1, 1, 7, 2]

d={}
for e, v in enumerate(l):
    if v in d.keys():
        d[v].append(e)
    else:
        d[v]= [e]

print(d)

{2: [0, 4], 1:[1, 2], 7: [3]}

Upvotes: 0

Views: 76

Answers (1)

user2390182
user2390182

Reputation: 73450

You could use a defaultdict to smoothen your code, but other than that, it's fine:

from collections import defaultdict

d = defaultdict(list)
for i, x in enumerate(l):
    d[x].append(i)

Alternativey, you can use the setdefault method to access dict values:

d = {}
for i, x in enumerate(l):
    d.setdefault(x, []).append(i)

Upvotes: 3

Related Questions