Home > Software engineering >  Sort list of objects in python using custom sort logic function with cmp_to_key
Sort list of objects in python using custom sort logic function with cmp_to_key

Time:03-03

I have a list of objects in python, where a single object has 2 attributes ie. a and b, a can be either None or dict and b is an int or None, I want the resultant list to be sorted like:

  1. It should have first all objects with a equal to None.
  2. Then it should have all objects with a not equal to None.
  3. In 1, 2 if those objects have b (b is int) then sort them with b.

Example result:

[
    Obj(a=None, b=2), 
    Obj(a=None, b=5), 
    Obj(a=None, b=None), 
    Obj(a=dict, b=1), 
    Obj(a=dict, b=4), 
    Obj(a=dict, b=None)
]

CodePudding user response:

This will do it using sorted(), and a similar approach would work with the sort() method of the list datatype:

        class Obj:
            def __init__(self, a, b):
                self.a = a
                self.b = b
        
        input = [
            Obj(a=dict(), b=1), 
            Obj(a=dict(), b=None),
            Obj(a=None, b=5), 
            Obj(a=None, b=None), 
            Obj(a=dict(), b=4), 
            Obj(a=None, b=2),
        ]
        output = sorted(input, key=lambda x: (x.a is not None, x.b is None, x.b))
        [print(f"Obj(a={'dict' if x.a is not None else 'None'}, b={x.b})") for x in output]

Output:

Obj(a=None, b=2)
Obj(a=None, b=5)
Obj(a=None, b=None)
Obj(a=dict, b=1)
Obj(a=dict, b=4)
Obj(a=dict, b=None)
  • Related