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>Sort using enumerate to get the sorted indexes and just use the indexes to sort the other lists:</p>

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

l = [i for i, _ in sorted(enumerate(dict1[2]), key=itemgetter(1))]


for v in dict1.values():
    v[:] = (v[i] for i in l)
print(dict1)
</code></pre>

<p>Or if you want a new dict:</p>

<pre><code>l = [i for i, _ in sorted(enumerate(dict1[2]), key=itemgetter(1))]
new = {k: [v[i] for i in l] for k, v in dict1.items()}
</code></pre>

<p>Or if you don't mind tuples:</p>

<pre><code>new = {k: itemgetter(*l)(v) for k, v in dict1.items()})
</code></pre>

python list dictionary