Consider a list of dict
s 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?
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.
just write d. items() , it will work, by default on iterating the name of dict returns only the keys.
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.
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With