[英]Iterate through dictionary with respect to nested dictionary
I have a nested dictionary as follows: 我有一个嵌套字典如下:
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}
}
I would like to iterate through the containing dictionary (with keys loan1
through loan6
) in order of the key containing the dictionary with the highest 'rate' value in its respective nested dictionary. 我想按照包含在其各自嵌套字典中具有最高'rate'值的字典的键的顺序遍历包含字典(使用keys loan1
到loan6
)。 That is, I would like to iterate in order of loan3
, loan4
, loan1
, loan2
, loan6
, loan5
也就是说,我想按loan3
, loan4
, loan1
, loan2
, loan6
, loan5
顺序进行迭代
What is the easiest way to do this? 最简单的方法是什么?
Thanks 谢谢
I believe you want: 我相信你想:
sorted(student_loan_portfolio.items(), key=lambda (k,v): v['rate'], reverse=True)
(Thanks @MarkReed, you're right. To sort in descending order we need either -v['rate']
or, as I've shown above, passing reverse=True
to sorted
.) (感谢@MarkReed,你说得对。要以降序排列,我们需要或者-v['rate']
或者,正如我上面显示,通过reverse=True
来sorted
。)
You can sort the values like this: 您可以像这样对值进行排序:
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})]
See this page for more details on how to complex sorting in python works: http://wiki.python.org/moin/HowTo/Sorting/ 有关如何在python中复杂排序的详细信息,请参阅此页面: http : //wiki.python.org/moin/HowTo/Sorting/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.