[SOLVED] How to sorting (ASCENDING) by key using Python dictionary

Issue

This Content is from Stack Overflow. Question asked by coder_noob

I have several dictionary

{
('ABD12-GOU10', 'ASS 4W LINE 3'):[15,5],
('ABD13-GOU11', 'ASS 4W LINE 1'):[7,5],
('ABD13-GOU11', 'ASS 4W LINE 1'):[22,5],
('ABD14-GOU13', 'ASS 4W LINE 1'):[12,5],
('ABD14-GOU19', 'ASS 4W LINE 2'):[4,5],
('ABD14-GOU10', 'ASS 4W LINE 3'):[2,5],
('ABD14-GOU13', 'ASS 4W LINE 4'):[18,5],
('ABD14-GOU12', 'ASS 4W LINE 5'):[9,5],
('ABD14-GOU11', 'ASS 4W LINE 6'):[3,5],
}

How to grouping by key 2 ex: ASS 4W LINE 1 and order by key 1 ex: ABD12-GOu10. I want like this:

{
('ABD13-GOU11', 'ASS 4W LINE 1'):[7,5],
('ABD13-GOU11', 'ASS 4W LINE 1'):[22,5],
('ABD14-GOU13', 'ASS 4W LINE 1'):[12,5],
('ABD14-GOU19', 'ASS 4W LINE 2'):[4,5],
('ABD12-GOU10', 'ASS 4W LINE 3'):[15,5],
('ABD14-GOU10', 'ASS 4W LINE 3'):[2,5],
('ABD14-GOU13', 'ASS 4W LINE 4'):[18,5],
('ABD14-GOU12', 'ASS 4W LINE 5'):[9,5],
('ABD14-GOU11', 'ASS 4W LINE 6'):[3,5],
}



Solution

Keep in mind that Python dictkeep order since Python 3.6 only

I use numpy for argsorting, but you can use anything
You can do:

import numpy as np
keys = list(D.keys())
sorted_D = {
    keys[i]: D[keys[i]] for i in np.argsort([k[1] for k in keys]) 
}

output:

 {('ABD13-GOU11', 'ASS 4W LINE 1'): [22, 5],
 ('ABD14-GOU13', 'ASS 4W LINE 1'): [12, 5],
 ('ABD14-GOU19', 'ASS 4W LINE 2'): [4, 5],
 ('ABD12-GOU10', 'ASS 4W LINE 3'): [15, 5],
 ('ABD14-GOU10', 'ASS 4W LINE 3'): [2, 5],
 ('ABD14-GOU13', 'ASS 4W LINE 4'): [18, 5],
 ('ABD14-GOU12', 'ASS 4W LINE 5'): [9, 5],
 ('ABD14-GOU11', 'ASS 4W LINE 6'): [3, 5]}

However, this will only sort on index 1 of the key, so it might have different behaviours on dictionary with keys with same index 1 value.

EDIT:

As said in a comment, your original dictionary has identical keys, so the output above has not the same number of values


This Question was asked in StackOverflow by coder_noob and Answered by PlainRavioli It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?