How can I sort dictionary values by one key?

DarkDrassher34 :

All,

I am struggling with sorting a dictionary containing multiple values for each key by a single key. I have the following dictionary

{ 
     'time': [2, 1, 3], 
     'x_coordinates': [3, 5, 4], 
     'y_coordinates': [6, 7, 8]
}

and desire the following as an output:

{
     'time': [1, 2, 3], 
     'x_coordinates': [5, 3, 4], 
     'y_coordinates': [7, 6, 8]
}

How can I achieve this in the most efficient way possible? I have tried following the internet for suggestions, but there is nothing about sorting multi-value keys by a single key. Any help will be appreciated.

kederrac :
d = {'time': [2, 1, 3], 'x_coordinates': [3, 5, 4], 'y_coordinates': [6, 7, 8]}

key = 'time'
index = [f for f, _ in sorted(enumerate(d[key]), key=lambda x : x[1])]
d = {k : [v[i] for i in index] for k, v in d.items()}

output:

{'time': [1, 2, 3], 'x_coordinates': [5, 3, 4], 'y_coordinates': [7, 6, 8]}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=10212&siteId=1