Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering a list of dictionaries in python

I've got a python list of dictionaries:

mylist = [
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'}
]

Whats the most efficient/cleanest way to order that list by weight then factor (numerically). The resulting list should look like:

mylist = [
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
]
like image 761
mluebke Avatar asked May 14 '09 01:05

mluebke


People also ask

Can you order dictionaries in Python?

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

How do I filter a dictionary list in Python?

We can easily search a list of dictionaries for an item by using the filter() function with a lambda function. In Python3, the filter() function returns an object of the filter class. We can convert that object into a list with the list() function.


1 Answers

mylist.sort(key=lambda d: (d['weight'], d['factor']))

or

import operator
mylist.sort(key=operator.itemgetter('weight', 'factor'))
like image 169
dF. Avatar answered Oct 02 '22 16:10

dF.