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

Sorting python dictionary based on keys which is alphanumeric values

I am new to python. In Python, I want to sort list of dictionary items first based on ‘year’ key and later with key which is alphanumeric ie P1, P2, P3.

Code snippet is as follows:

[
    {"P9": 0, "year": 2023},
    {"P13": 0, "year": 2023},
    {"P10": 0, "year": 2023},
    {"P11": 121200, "year": 2022},
    {"P12": 0, "year": 2023},
]

Which first sorted by year in acending order becomes:

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

[
    {"P11": 121200, "year": 2022},
    {"P9": 0, "year": 2023},
    {"P13": 0, "year": 2023},
    {"P10": 0, "year": 2023},
    {"P12": 0, "year": 2023},
]

Again later sorted by period key ie, P1,P2,P3 etc becomes:

[
    {"P11": 121200, "year": 2022},
    {"P9": 0, "year": 2023},
    {"P10": 0, "year": 2023},
    {"P12": 0, "year": 2023},
    {"P13": 0, "year": 2023},
]

Above is the expected output,
Now I don’t know how do I sort it like this

>Solution :

For sorting first base years then sorting base first key of each dict you can catch number and convert to int then sorting like below:

>>> sorted(lst_dct, key=lambda x: (x['year'], int(list(x.keys())[0][1:])))
[{'P11': 121200, 'year': 2022},
 {'P9': 0, 'year': 2023},
 {'P10': 0, 'year': 2023},
 {'P12': 0, 'year': 2023},
 {'P13': 0, 'year': 2023}]
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