在python中排序字典列表

时间:2009-05-14 01:41:04

标签: python list dictionary

我有一个字典的python列表:

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'}
]

按重量排序该列表的最有效/最干净的方法是什么(数值)。结果列表应如下所示:

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'},
]

4 个答案:

答案 0 :(得分:23)

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

import operator
mylist.sort(key=operator.itemgetter('weight', 'factor'))

答案 1 :(得分:1)

以下内容应该有效:

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)

答案 2 :(得分:1)

我接受了dF对灵感的回答,但这是我最终确定的方案:

@staticmethod
def ordered_list(mylist):
    def sort_func(d):
        return (d['weight'], d['factor'])

    mylist.sort(key=sort_func)

答案 3 :(得分:-1)

decoratedlist = [(item[weight], item) for item in mylist]
decoratedlist.sort()
results = [item for (key, item) in decoratedlist]