Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort a list of python Django objects?

In Django, I have a model object in a list.

[object, object, object]

Each object has ".name" which is the title of the thing.

How do I sort alphabetically by this title?

This doesn't work:

catlist.sort(key=lambda x.name: x.name.lower())
like image 595
TIMEX Avatar asked May 26 '10 20:05

TIMEX


People also ask

Can you sort a list of objects in Python?

Python lists have a built-in list. sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable.

How do you sort a list of objects in ascending order in Python?

Method 2: Using sorted() method The sorted() function returns a sorted list of the iterable object given. You can choose between ascending and descending order. Numbers are sorted numerically, while strings are arranged alphabetically.

How do you sort an array of objects based on a property in Python?

A simple solution is to use the list. sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse.


1 Answers

catlist.sort(key=lambda x: x.name.lower())
like image 134
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 18:09

Ignacio Vazquez-Abrams