Python: sorting the lists of dictionary based on the indices of one list
<p>So I have dict like the following:</p>

<pre><code>dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]}
</code></pre>

<p>How can I sort the lists in <code>dict1</code> based on the indices that would sort one of the lists. Such as the sorted indices of list </p>

<pre><code>[11, 10, 9, 8, 7]
</code></pre>

<p>which is</p>

<pre><code>[4, 3, 2, 1, 0]
</code></pre>

<p>So the new <code>dict1</code> will be:</p>

<pre><code>dict1 = {1: [3, 4, 2, 1, -1], 2: [7, 8, 9, 10, 11]}
</code></pre>

<p>I have tried the code like this:</p>

<pre><code>sorted(dict1.items(), key=lambda t: t[1])
</code></pre>

<p>But still cannot figure it out? I can use a for loop to do this work but I believe there exist a more pythonic way. Any idea?</p>

<p>One way would be to compute the index list and apply it to all lists:</p>

<pre><code>&gt;&gt;&gt; dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]}
&gt;&gt;&gt; basis = dict1[2]
&gt;&gt;&gt; indexes = sorted(range(len(basis)), key=basis.__getitem__)
&gt;&gt;&gt; for lst in dict1.values():
        lst[:] = [lst[i] for i in indexes]

&gt;&gt;&gt; dict1
{1: [3, 4, 2, 1, -1], 2: [7, 8, 9, 10, 11]}
</code></pre>

<p>If you're ok with "the first" list determining the order (you only said <em>"based on [...] one of the lists"</em>), you could also build columns and sort those:</p>

<pre><code>&gt;&gt;&gt; dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]}
&gt;&gt;&gt; dict(zip(dict1.keys(), zip(*sorted(zip(*dict1.values())))))
{1: (-1, 1, 2, 3, 4), 2: (11, 10, 9, 7, 8)}
</code></pre>

python list dictionary