cdelsola
cdelsola

Reputation: 437

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. That is, I would like to iterate in order of loan3, loan4, loan1, loan2, loan6, loan5

What is the easiest way to do this?

Thanks

Upvotes: 4

Views: 303

Answers (2)

Nihathrael
Nihathrael

Reputation: 515

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/

Upvotes: 0

Jamey Sharp
Jamey Sharp

Reputation: 8491

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.)

Upvotes: 3

Related Questions