Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over list of dicts in order of property [duplicate]

Tags:

python

sorting

Consider a list of dicts with a date property and an amount property:

transactions = [
    {'date': '2013-05-12', 'amount': 1723},
    {'date': '2013-07-23', 'amount': 4523},
    {'date': '2013-02-01', 'amount': 2984},
]

I would like to add a balance property, but to do so I must iterate over the list in date order:

balance = 0
for t in transactsions:    # Order by date
    balance += t['amount']
    t['balance'] = balance

How would one go about this? If I were to replace the dicts with Transaction objects having date and amount properties, would it then be possible?

like image 636
dotancohen Avatar asked Nov 11 '13 07:11

dotancohen


People also ask

How do I iterate a list of dictionaries in Python?

In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.

How do you iterate over a nested dictionary in Python?

just write d. items() , it will work, by default on iterating the name of dict returns only the keys.

Can a Python set contain dictionaries?

You can access the dictionary values with their respective keys. To access a specific value in the dictionary data set, you need to index the right key. Dictionaries in Python are mutable and the elements in a dictionary can be added, removed, modified, and changed accordingly.


1 Answers

Yes, both is possible with "key" keyword argument of function sorted(). Take a look at the snippet:

>>> l = [1, 3, 2]
>>> sorted(l)
[1, 2, 3]
>>> sorted(l, key=lambda x: x**2)
[1, 2, 3]
>>> sorted(l, key=lambda x: -x)
[3, 2, 1]

You can pass a callable as "key" keyword argument to sorted() and the callable will be used to provide a sorting key. For your first problem you could wrap transactions in sorted and pass lambda x: x['date] as a "key". For objects just change "key" to something like lambda x: x.date .

like image 150
peroksid Avatar answered Oct 13 '22 23:10

peroksid