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 sort list in a sequence with python?

I have a list of dict like this and here D referes to Day and H refers to Hour. I want to sort the list based on those value. How can I do this ?

First Hour should be sorted and then Days should be sorted.

my_list = [
    {"key1":"123D", "key2":"123D"}, {"key1":"48H", "key2":"48H"},  
    {"key1":None, "key2":"154D"}, {"key1":"122D", "key2":"122D"},
    {"key1":"5D", "key2":"5D"} 
]


sorted_list = sorted(
            my_list,
            key=lambda k: (
                (
                    k["key1"] is None,
                    int(k["key1"][:-1]) if k["key1"] else None,
                ),
                (
                   k["key2"] is None,
                    int(k["key2"][:-1]) if k["key2"] else None,
               ),
            ),
        )

Currently I am getting the result like this:

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

 [{'key1': '5D', 'key2': '5D'},
 {'key1': '48H', 'key2': '48H'},
 {'key1': '122D', 'key2': '122D'},
 {'key1': '123D', 'key2': '123D'},
 {'key1': None, 'key2': '154D'}]

But what I want is

 [{'key1': '48H', 'key2': '48H'},
 {'key1': '5D', 'key2': '5D'},
 {'key1': '122D', 'key2': '122D'},
 {'key1': '123D', 'key2': '123D'},
 {'key1': None, 'key2': '154D'}]

>Solution :

You need to convert the different representations to a common time unit. Convert the days to hours multiplying by 24:

def key(d):

    k1 = (1, None)
    if d["key1"] is not None:
        v1 = int(d["key1"][:-1]) * (24 if "D" in d["key1"] else 1)
        k1 = (0, v1)

    k2 = (1, None)
    if d["key2"] is not None:
        v2 = int(d["key2"][:-1]) * (24 if "D" in d["key2"] else 1)
        k2 = (0, v2)

    return k1, k2


res = sorted(my_list, key=key)
print(res)

Output

[{'key1': '48H', 'key2': '48H'},
 {'key1': '5D', 'key2': '5D'},
 {'key1': '122D', 'key2': '122D'},
 {'key1': '123D', 'key2': '123D'},
 {'key1': None, 'key2': '154D'}]
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