[英]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.