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>Try this out :</p>

<pre><code>data = np.array(data)
dic = {}

for i, val in enumerate(data):
    if val in dic.keys():
        dic[val].append(i)
    else:
        dic[val]=[]
        dic[val].append(i)
</code></pre>

python numpy