CodexBloom - Programming Q&A Platform

Sorting a List of Custom Objects by Multiple Attributes in Python - guide with None Values

👀 Views: 14 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
python sorting custom-objects Python

I'm trying to sort a list of custom objects in Python based on multiple attributes, but I'm running into issues when some of those attributes have `None` values. My custom class is defined like this: ```python class Employee: def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary ``` I have a list of employees and I want to sort them first by age (ascending) and then by salary (descending). Here's how I've attempted to sort the list: ```python employees = [ Employee('Alice', 30, 70000), Employee('Bob', None, 50000), Employee('Charlie', 25, 80000), Employee('David', 30, None), Employee('Eve', 35, 60000) ] sorted_employees = sorted(employees, key=lambda e: (e.age, -e.salary if e.salary is not None else float('-inf'))) ``` This works fine until it encounters the `None` values for `age` or `salary`. When I run this code, I get a `TypeError`: `'<=' not supported between instances of 'NoneType' and 'int'`. I understand that Python need to compare `None` with integers, but I want to handle these cases gracefully. Is there a preferred way to sort this list, treating `None` values as the lowest priority? Ideally, employees with `None` for age should come last, while those with a salary of `None` should be sorted lower than those with a salary. Any suggestions on how to modify my sorting logic? I'm currently using Python 3.10. I'm working on a API that needs to handle this. I'm open to any suggestions.