getting list of indices of each value of list in a pythonic way
<p>I have a list <code>data</code> of values, and I want to return a dictionary mapping each value of <code>data</code> to a list of the indices where this value appears.</p>

<p>This can be done using this code:</p>

<pre><code>data = np.array(data)
{val: list(np.where(data==val)[0]) for val in data}
</code></pre>

<p>but this runs in O(n^2), and this is too slow for long lists. Can an O(n) solution be coded using a "pythonic" syntax? (it can be done with creating an empty list and updating it in a loop, but I understand this is not recommended in python.)</p>

<p>You can use a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> of <code>lists</code> to achieve this in O(n):</p>

<pre><code>from collections import defaultdict

d = defaultdict(list)
for idx, item in enumerate(data):
    d[item].append(idx)
</code></pre>

<p>For example, if <code>data</code> contains the string <code>'abcabccbazzzqa'</code>:</p>

<pre><code>d = defaultdict(list)
for idx, item in enumerate('abcabccbazzzqa'):
    d[item].append(idx)

&gt;&gt;&gt; d
defaultdict(&lt;type 'list'&gt;, {'a': [0, 3, 8, 13], 'q': [12], 'c': [2, 5, 6], 'b': [1, 4, 7], 'z': [9, 10, 11]})
&gt;&gt;&gt; d['a']
[0, 3, 8, 13]
</code></pre>

python numpy