繁体   English   中英

排序多维字典

[英]Sort Multi-dimensional 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)

但这两个字段的降序排列。

@ InsepctorG4dget正确,因为您只反转一个键,而一个键不是(轻松)可逆的-可行的方法是放弃reverse键并反转可逆键:

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

如果您不介意就地进行稳定排序和修改列表,请使用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')]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM