Sorting a List of Custom Objects by Dynamic Criteria in Python - implementing Incorrect Sorting Order
I'm converting an old project and I'm stuck trying to After trying multiple solutions online, I still can't figure this out... I'm working with a list of custom objects in Python where I need to sort them based on dynamic criteria provided at runtime. The objects are instances of a class `Product` that contains attributes such as `name`, `price`, and `rating`. The scenario is that depending on user input, I may need to sort by either `price` or `rating` or even by both in some cases. However, I'm running into issues where the sorting doesn't behave as expected, especially when sorting by multiple criteria. Hereโs a snippet of my `Product` class and how I attempt to sort the list: ```python class Product: def __init__(self, name, price, rating): self.name = name self.price = price self.rating = rating def __repr__(self): return f"Product(name={self.name}, price={self.price}, rating={self.rating})" products = [ Product('A', 30, 4.5), Product('B', 20, 5.0), Product('C', 30, 3.0), Product('D', 20, 4.0) ] sort_by = 'price' # Change this to 'rating' or a tuple ('price', 'rating') for multi-criteria if isinstance(sort_by, tuple): products.sort(key=lambda x: (x.price, x.rating)) else: products.sort(key=lambda x: getattr(x, sort_by)) ``` When I run this code with `sort_by` set to `'price'`, I expect the products to be sorted in ascending order of their price. However, when I also try sorting by `rating` if the prices are equal, it seems to not sort correctly. Specifically, I expect product 'A' and 'C' (both priced at 30) to be ordered by their rating, but they appear in the wrong order in the output. The output Iโm getting is: ``` [Product(name=A, price=30, rating=4.5), Product(name=C, price=30, rating=3.0), Product(name=B, price=20, rating=5.0), Product(name=D, price=20, rating=4.0)] ``` I also tried using the `sorted()` function with the same key logic, but I still end up with the same incorrect order. I suspect it might be related to how the sorting is implemented or how the lambda function processes the sorting criteria. Could someone guide to understand why this isn't giving the expected behavior? Whatโs the best way to implement dynamic multi-criteria sorting in this scenario? I'm using Python 3.11 in this project. Any ideas what could be causing this? I'm coming from a different tech stack and learning Python. I've been using Python for about a year now. Is this even possible?