Kale
Kale

Reputation: 3

Sort a lists within a dictionary using data of one of the lists

I have a dictionary which structure is as follows:

dic = {'NODE':[5,4,3,1,2],'sh1':[300.5,40.345,9.0,325.2,3.65], 'sh2':[50.6,48.5,2.1,0.0,90.1254], 'sh3':[780.5,54.5,89.0,35.64,2.85]}

I would like to organize the lists within the dictionary according to the NODE list, so the dictionary would be as:

dic = {'NODE':[1,2,3,4,5],'sh1':[325.2,3.65,9.0,40.345,300.5], 'sh2':[0.0,90.1254,2.1,48.5,50.6], 'sh3':[35.64,2.85,89.0,54.5,780.5]}

Probably there is an easy solution to this, but I'm very new in python, specially with this dictionary concept.

Thank you in advance for your help.

Upvotes: 0

Views: 41

Answers (2)

Booboo
Booboo

Reputation: 44053

dic = {'NODE':[5,4,3,1,2],'sh1':[300.5,40.345,9.0,325.2,3.65], 'sh2':[50.6,48.5,2.1,0.0,90.1254], 'sh3':[780.5,54.5,89.0,35.64,2.85]}

# the current positions in dict['NODE'] where the new values should come from, i.e. [3, 4, 2, 1, 0]
from_positions = list(map(lambda x: x[1], sorted((x, idx) for idx, x in enumerate(dic['NODE']))))
for key, value in dic.items():
    new_value = [value[from_position] for from_position in from_positions]
    dic[key] = new_value
print(dic)

Prints:

{'NODE': [1, 2, 3, 4, 5], 'sh1': [325.2, 3.65, 9.0, 40.345, 300.5], 'sh2': [0.0, 90.1254, 2.1, 48.5, 50.6], 'sh3': [35.64, 2.85, 89.0, 54.5, 780.5]}

Upvotes: 0

dankal444
dankal444

Reputation: 4148

You can use np.argsort to get indices that you will use to sort all the lists:

import numpy as np
dic = {'NODE':[5,4,3,1,2],'sh1':[300.5,40.345,9.0,325.2,3.65], 'sh2':[50.6,48.5,2.1,0.0,90.1254], 'sh3':[780.5,54.5,89.0,35.64,2.85]}

sort_indices = np.argsort(dic['NODE'])
sorted_dic = {}
for key in dic:
    sorted_dic[key] = np.asarray(dic[key])[sort_indices].tolist()
print(sorted_dic)

Result:

{'NODE': [1, 2, 3, 4, 5], 'sh1': [325.2, 3.65, 9.0, 40.345, 300.5], 'sh2': [0.0, 90.1254, 2.1, 48.5, 50.6], 'sh3': [35.64, 2.85, 89.0, 54.5, 780.5]}

Upvotes: 1

Related Questions