user16054 - 8 months ago 50

Python Question

I'm looking for a function that would do what the function

`indices`

`indices( numpy.array([[1, 2, 3], [2, 3, 4]]) )`

{1: [(0,0)], 2: [(0,1),(1,0)], 3: [(0,2),(1,1)], 4: [(1,2)]}

Specifically, I want to produce a dictionary whose keys are the unique elements in the flattened array and whose values are lists of the full indices of the respective key.

I've looked at the

`where`

Notes: I'm using Python 2.7

Answer

Given that your desired output is a dictionary, I don't think there's going to be an efficient way to do this with NumPy operations. Your best bet will probably be something like

```
import collections
import itertools
d = collections.defaultdict(list)
for indices in itertools.product(*map(range, a.shape)):
d[a[indices]].append(indices)
```

Source (Stackoverflow)