Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a Custom Sorting Function for Dictionary Key Values?

I have a dictionary whose key values are kind of like this,

CC-1A
CC-1B
CC-1C
CC-3A
CC-3B
CC-5A
CC-7A
CC-7B
CC-7D
SS-1A
SS-1B
SS-1C
SS-3A
SS-3B
SS-5A
SS-5B

lst = ['CC-1A', 'CC-1B', 'CC-1C', 'CC-3A', 'CC-3B', 'CC-5A', 'CC-7A', 'CC-7B', 
       'CC-7D', 'SS-1A', 'SS-1B', 'SS-1C', 'SS-3A', 'SS-3B', 'SS-5A', 'SS-5B']
d = dict.fromkeys(lst)

^Not exactly in this order, but in fact they are all randomly placed in the dictionary as key values.

Now, I want to sort them. If I use the built in function to sort the dictionary, it sorts all the key values according to the order given above.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, I want the dictionary to be first sorted based upon the values after the – sign (i.e. 1A, 1B, 1C etc.) and then based upon the first two characters.

So, for the values given above, following would be my sorted list,

    CC-1A
    CC-1B
    CC-1C
    SS-1A
    SS-1B
    SS-1C
    CC-3A
    CC-3B
    SS-3A
    SS-3B
    CC-5A
    and so on
  1. First, sorting is done based upon the "4th" character in the keys. (that is, 1, 3, etc.)

  2. Then sorting is done based upon the last character (i.e. A, B etc.)

  3. Then sorting is done based upon the first two characters of the keys (i.e. CC, SS etc.)

Is there any way to achieve this?

>Solution :

You could use a custom function that implements your rule as sorting key:

def get_order(tpl):
    s = tpl[0].split('-')
    return (s[1][0], s[0], s[1][1])


out = dict(sorted(d.items(), key=get_order))

Output:

{'CC-1A': None, 'CC-1B': None, 'CC-1C': None, 'SS-1A': None, 'SS-1B': None, 'SS-1C': None, 'CC-3A': None, 'CC-3B': None, 'SS-3A': None, 'SS-3B': None, 'CC-5A': None, 'SS-5A': None, 'SS-5B': None, 'CC-7A': None, 'CC-7B': None, 'CC-7D': None}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading