I'm trying to add the sum of objects from a database but so far I have found no success
test = [{'shares': 5}, {'shares': 1}]
# print sum of the two shares (5+1=6)
I've tried to use test['shares']
to print but it results in the error:
list indices must be integers or slices, not str
I've tried sum(test.value())
but creates the error
'list' object has no attribute 'values'
And sum(test)
creates:
unsupported operand type(s) for +: 'int' and 'dict'
It seems like the objects are wrapped in a list but I do not know how to unwrap it?
One nice way would be
sum(x['shares'] for x in test)
Why does this work?
Given a dictionary d = {'shares': 7}
, then to get the value 7
, you call d['shares']
.
You want to do that for each dictionary in the list test
, so you want to look at x['shares']
for each x
in test
.
In Python, the function sum
can accept something called a "generator expression", which is what we did here.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments