排序多维字典

2024-04-23 07:27:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本如下格式的词典。我想根据“score”值的降序对字典进行排序,如果是并列的,则按“title”值的字典顺序排序。

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

因此输出应为:

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

我试过了:

^{pr2}$

但这两个字段都是按降序排序的。


Tags: 字典排序顺序title格式词典scoreabcd
1条回答
网友
1楼 · 发布于 2024-04-23 07:27:46

@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两次:

^{pr2}$

结果:

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

请注意,您的预期输出表明title值在排序时反转。

相关问题 更多 >