如何在 Python 中通过 'votes' 对这个字典进行排序?
{
1 : {
'votes' : 2,
'id' : 10
},
2 : {
'votes' : 10,
'id' : 12
},
3 : {
'votes' : 98,
'id' : 14
}
}
结果:
{
3 : {
'votes' : 98,
'id' : 14
},
2 : {
'votes' : 10,
'id' : 12
},
1 : {
'votes' : 2,
'id' : 10
}
}
请您参考如下方法:
你可以使用 OrderedDict :
>>> from collections import OrderedDict
>>> od = OrderedDict(sorted(d.items(),
key=lambda t: t[1]['votes'],
reverse=True))
>>> od
OrderedDict([(3, {'votes': 98, 'id': 14}),
(2, {'votes': 10, 'id': 12}),
(1, {'votes': 2, 'id': 10})])
其中 d 是您的原始字典。
