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.)
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
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With