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:

[
    {"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}]

Leave a Reply