我有一本格式如下的字典。我想根据“分数”值的值按降序对字典进行排序,如果出现平局,则按“标题”值的字典顺序排序。
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'])
)
如果你不介意的话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')]
请注意,您的预期输出表明 title
值在排序时不会反转。
关于python - 排序多维字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33246230/