我有一个嵌套字典如下:
student_loan_portfolio = {
'loan1': {'rate': .078, 'balance': 1000, 'payment': 100, 'prepayment': 0},
'loan2': {'rate': .0645, 'balance': 10, 'payment': 5, 'prepayment': 0},
'loan3': {'rate': .0871, 'balance': 250, 'payment': 60, 'prepayment': 0},
'loan4': {'rate': .0842, 'balance': 200, 'payment': 37, 'prepayment': 0},
'loan5': {'rate': .054, 'balance': 409, 'payment': 49, 'prepayment': 0},
'loan6': {'rate': .055, 'balance': 350, 'payment': 50, 'prepayment': 0}
}
我想按照包含在其各自嵌套字典中具有最高'rate'值的字典的键的顺序遍历包含字典(使用键loan1
到loan6
)。也就是说,我想按loan3
,loan4
,loan1
,loan2
,loan6
,loan5
最简单的方法是什么?
由于
答案 0 :(得分:3)
我相信你想要:
sorted(student_loan_portfolio.items(), key=lambda (k,v): v['rate'], reverse=True)
(感谢@MarkReed,你是对的。要按降序排序,我们需要-v['rate']
或者如上所示,将reverse=True
传递给sorted
。)< / p>
答案 1 :(得分:0)
您可以按如下方式对值进行排序:
sorted(student_loan_portfolio.items(), key=lambda (name,portfolio): portfolio['rate'], reverse=True)
[('loan3', {'rate': 0.0871, 'balance': 250, 'payment': 60, 'prepayment': 0}), ('loan4', {'rate': 0.0842, 'balance': 200, 'payment': 37, 'prepayment': 0}), ('loan1', {'rate': 0.078, 'balance': 1000, 'payment': 100, 'prepayment': 0}), ('loan2', {'rate': 0.0645, 'balance': 10, 'payment': 5, 'prepayment': 0}), ('loan6', {'rate': 0.055, 'balance': 350, 'payment': 50, 'prepayment': 0}), ('loan5', {'rate': 0.054, 'balance': 409, 'payment': 49, 'prepayment': 0})]
有关如何在python中复杂排序的更多详细信息,请参阅此页面: http://wiki.python.org/moin/HowTo/Sorting/