Quickly convert numpy arrays with index to dict of numpy arrays keyed on that index
<p>I have a set of numpy arrays. One of these is a list of "keys", and I'd like to rearrange the arrays into a dict of arrays keyed on that key. My current code is:</p>

<pre><code>for key, val1, val2 in itertools.izip(keys, vals1, vals2):
    dict1[key].append(val1)
    dict2[key].append(val2)
</code></pre>

<p>This is pretty slow, since the arrays involved are millions of entries long, and this happens many times. Is it possible to rewrite this in vectorized form? The set of possible keys is known ahead of time, and there are ~10 distinct keys.</p>

<p><strong>Edit:</strong> If there are k distinct keys and the list is n long, the current answers are O(nk) (iterate once for each key) and O(n log n) (sort first). I'm still looking for an O(n) vectorized solution, though. This is hopefully possible; after all, the easiest possible nonvectorized thing (i.e. what I already have) is O(n).</p>

<p>Let's import numpy and create some sample data:</p>

<pre><code>&gt;&gt;&gt; import numpy as np
&gt;&gt;&gt; keys = np.array(('key1', 'key2', 'key3', 'key1', 'key2', 'key1'))
&gt;&gt;&gt; vals1 = np.arange(6)
&gt;&gt;&gt; vals2 = np.arange(10, 16)
</code></pre>

<p>Now, let's create the dictionary:</p>

<pre><code>&gt;&gt;&gt; d1 = {}; d2 = {}
&gt;&gt;&gt; for k in set(keys):
...   d1[k] = vals1[k==keys]
...   d2[k] = vals2[k==keys]
... 
&gt;&gt;&gt; d1
{'key3': array([2]), 'key2': array([1, 4]), 'key1': array([0, 3, 5])}
&gt;&gt;&gt; d2
{'key3': array([12]), 'key2': array([11, 14]), 'key1': array([10, 13, 15])}
</code></pre>

<p>The idea behind <code>numpy</code> is that C code is much faster than python and numpy provides many common operations coded at the C level.
As you mentioned that there were only "~10 distinct keys,"  that means that the python loop is done only 10 or so times.  The rest is C.</p>

python numpy vectorization