8

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?

dotancohen
  • 30,064
  • 36
  • 138
  • 197
  • Yes, Steve! I did find that in the sidebar after posting, but searching did not uncover it. I'll therefore leave this question here to possibly help in searches. – dotancohen Nov 11 '13 at 07:38
  • You can't close it anymore. I have no idea why people are bothering to answer, though... – Steve P. Nov 11 '13 at 07:41

3 Answers3

3

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 .

peroksid
  • 890
  • 6
  • 17
0

Found it! From this answer:

for t in sorted(transactions, key=lambda k: k['date']):
    balance += t['amount']
    t['balance'] = balance

Funny how searching did not lead to that answer, but after posting it appears at the top of the sidebar!

Community
  • 1
  • 1
dotancohen
  • 30,064
  • 36
  • 138
  • 197
0

Careful, you have a typo in your loop (transactsion)

transactions.sort(key=lambda x:x['date'])
for t in transactions:
    balance += t['amount']
    t['balance'] = balance

This should do the trick, and this way your list remain sorted

Rudy Bunel
  • 784
  • 1
  • 7
  • 15
  • Perhaps that is Python2? In Python3 that throws a TypeError. I don't have Python2 here to test, and I did not specify which Python version in the question as I did not think that it mattered. – dotancohen Nov 11 '13 at 07:42
  • `.sort()` is an in-place sort function for lists, not dicts, as they are inherently not sorted. – Steve P. Nov 11 '13 at 07:46
  • No, you're right. Sort modify the list in place but can't be used here. I'll modify my answer. – Rudy Bunel Nov 11 '13 at 07:47
  • Updated.@SteveP., we don't want to sort the dict, what we do is sorting the list of dict so sort can be used. – Rudy Bunel Nov 11 '13 at 07:51