排序多维字典

时间:2015-10-20 20:27:48

标签: python sorting dictionary

我有一个字典,格式如下。我想根据"得分"的值来对字典进行排序。按降序排列的值,如果是平局,则按照标题的字典顺序排序"标题"值。

d = {
   '123':{
        'score': 100,
        'title': 'xyz'
    },
   '234':{
        'score': 50,
        'title': 'abcd'
    },
    '567':{
        'score': 50,
        'title': 'aaa'
    }
}

所以输出应该是:

  

[(100,xyz),(50,aaa),(50,abcd)]

我试过这个:

  print sorted(d.items(), key=lambda x: (x[1]['score'], x[1]['title']), reverse=True)

但它正按两个字段的降序排序。

1 个答案:

答案 0 :(得分:1)

@ InsepctorG4dget说得对,因为你只能倒转一把钥匙,而一把钥匙不是(轻松)可逆的 - 要走的路就是放弃reverse并倒转可逆钥匙:

items = sorted(
    d.items(),
    # note -x[1]['score'] is negated value
    key=lambda x: (-x[1]['score'], x[1]['title'])
)

如果您不注意就地stable-sorting并修改列表,请使用list.sort两次:

items = d.items()
# last key first
items.sort(key=lambda x: x[1]['title'])
# first key last
items.sort(key=lambda x: x[1]['score'], reverse=True)

结果:

>>> items
[('123', {'score': 100, 'title': 'xyz'}), ('567', {'score': 50, 'title': 'aaa'}), ('234', {'score': 50, 'title': 'abcd'})]

>>> [(x[1]['score'], x[1]['title']) for x in items]
[(100, 'xyz'), (50, 'aaa'), (50, 'abcd')]

请注意,排序时,您的预期输出结果显示{strong> 值<{>}}。