Search code examples
pythonsortingrating

how to sort the business id based on sort function in python


Example:

enter code here
businesses: [
    Business(id=1, rating=4.0, vegan_friendly=True, price=4, distance=10.0),
    Business(id=2, rating=2.5, vegan_friendly=False, price=2, distance=5.0),
    Business(id=3, rating=4.5, vegan_friendly=False, price=1, distance=1.0),
    Business(id=4, rating=3.0, vegan_friendly=True, price=2, distance=3.4),
    Business(id=5, rating=4.5, vegan_friendly=true, price=1, distance=6.3),
    Business(id=6, rating=3.5, vegan_friendly=True, price=2, distance=1.2),
]

sort the rating from highest to low based on id


Solution

  • # To sort the list in place...
    businesses.sort(key=lambda x: x.id, reverse=True)
    
    # To return a new list, use the sorted() built-in function...
    newlist = sorted(businesses, key=lambda x: x.id, reverse=True)