Reputation: 8829
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'},
]
Upvotes: 8
Views: 744
Reputation: 159
decoratedlist = [(item[weight], item) for item in mylist]
decoratedlist.sort()
results = [item for (key, item) in decoratedlist]
Upvotes: -1
Reputation: 8829
I accepted dF's answer for the inspiration, but here is what I ultimately settled on for my scenario:
@staticmethod
def ordered_list(mylist):
def sort_func(d):
return (d['weight'], d['factor'])
mylist.sort(key=sort_func)
Upvotes: 1
Reputation: 75845
mylist.sort(key=lambda d: (d['weight'], d['factor']))
or
import operator
mylist.sort(key=operator.itemgetter('weight', 'factor'))
Upvotes: 23
Reputation: 47471
Something along the lines of the following ought to work:
def cmp_dict(x, y):
weight_diff = y['weight'] - x['weight']
if weight_diff == 0:
return y['factor'] - x['factor']
else:
return weight_diff
myList.sort(cmp_dict)
Upvotes: 1