Iterate over list of dicts in order of property
This question already has an answer here:
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 .
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!
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
链接地址: http://www.djcxy.com/p/70774.html上一篇: 按列表在Python中排序?
下一篇: 按财产顺序重复列出所有的字典