简体   繁体   中英

How can I sort dictionary values by one key?

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.

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]}

It seems like in your program 'time' and 'position' are correlated. I think it will be easier for you to use a dataframe where each key of the dictionary corresponds to a variable, that way when you sort it by, for example, 'time', all the information regarding time will move to the first position and so on.

import pandas as pd

info=pd.DataFrame({'time': [2, 1, 3], 'x_coordinates': [3, 5, 4], 'y_coordinates': [6, 7, 8]})
info.sort_values(by='time', axis=0)

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM