Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of integers into dictionary of indices

I have a (large) integer array like

materials = [0, 0, 47, 0, 2, 2, 47]  # ...

with few unique entries and I'd like to convert it into a dictionary of indices, i.e.,

d = {
    0: [0, 1, 3],
    2: [4, 5],
    47: [2, 6],
    }

What's the most efficient way of doing so? (NumPy welcome.)

like image 959
Nico Schlömer Avatar asked Mar 11 '17 20:03

Nico Schlömer


1 Answers

no need for numpy, those are standard python structures, dict comprehension does that very well for your problem:

materials = [0, 0, 47, 0, 2, 2, 47]

d = {v : [i for i,x in enumerate(materials) if x==v] for v in set(materials)}

print(d)

result:

{0: [0, 1, 3], 2: [4, 5], 47: [2, 6]}

[i for i,x in enumerate(materials) if x==v] finds all the indexes of the element in the list (index only finds the first one)

In the first version of my answer I was iterating on the list itself, but that's a bit wasteful since it will overwrite the key several times when there are a lot of occurrences, and the inner list comprehension has n complexity so the overall complexity is not so good.

While I was writing this final comment, someone suggested to iterate on unique elements, which is good, so turn that input list to a set!

like image 199
Jean-François Fabre Avatar answered Sep 25 '22 17:09

Jean-François Fabre