Tryggast
Tryggast

Reputation: 197

Sorting a list with dictionaries, django

myFrom two models in django i have created a list of dictionarys where each dictonary is a row in a table I show in the client.

I would like to be able to sort this list for each of the different "columns".

objdict = []    
mydict = {
    'thing1': model1.val1,
    'thing2': model2.val1,
    'thing3': model2.val2,
    'thing4': model1.val2,
    'thing5': model1.val3,
}
objdict.append(mydict)

Say i would like to sort this list on thing1 in ascending order. How could I be able to acheive this?

Upvotes: 0

Views: 60

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

You should just be able to do:

sorted_objects = sorted(objdict, key=lambda k: k['thing1'])

will get you ascending order. For descending:

sorted_objects = sorted(objdict, key=lambda k: k['thing1'], reverse=True)

Upvotes: 3

Related Questions