Jianli Cheng - 1 year ago 68
Python Question

# Python: sorting the lists of dictionary based on the indices of one list

So I have dict like the following:

``````dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]}
``````

How can I sort the lists in
`dict1`
based on the indices that would sort one of the lists. Such as the sorted indices of list
`[11, 10, 9, 8, 7]`
, which is
`[4, 3, 2, 1, 0]`
. So the new
`dict1`
will be:

``````dict1 = {1: [3, 4, 2, 1, -1], 2: [7, 8, 9, 10, 11]}
``````

I have tried the code like this:

``````sorted(dict1.items(), key=lambda t: t[1])
``````

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?

One way would be to compute the index list and apply it to all lists:

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

>>> dict1
{1: [3, 4, 2, 1, -1], 2: [7, 8, 9, 10, 11]}
``````

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

``````>>> dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]}
>>> dict(zip(dict1.keys(), zip(*sorted(zip(*dict1.values())))))
{1: (-1, 1, 2, 3, 4), 2: (11, 10, 9, 7, 8)}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download