Prashant
Prashant

Reputation: 402

Sum of specific key-value in python dictionary

I have a school dictionary as follow-

{
    ID('6a15ce'): {
        'count': 5,
        'amount': 0,
        'r_amount': None,
        'sub': < subobj >
    }, ID('464ba1'): {
        'count': 2,
        'amount': 120,
        'r_amount': None,
        'sub': < subobj2 >
    }
}

I want to find out the sum of amount , doing as follow-

{k:sum(v['amount']) for k,v in school.items()}

but here I am getting error TypeError: 'int' object is not iterable what could be efficient way to achieve.

Upvotes: 1

Views: 2074

Answers (4)

jpp
jpp

Reputation: 164693

This is a functional solution:

from operator import itemgetter

res = sum(map(itemgetter('amount'), school.values()))

Upvotes: 0

Vasilis G.
Vasilis G.

Reputation: 7844

You can also do it using the map function:

result = sum(map(lambda i: i['amount'], school.values()))
print(result)

Output:

120

Upvotes: 0

Yserbius
Yserbius

Reputation: 1414

sum(map(lambda schoolAmount: schoolAmount.amount, school))

Upvotes: -2

ForceBru
ForceBru

Reputation: 44848

You can do:

result = sum(v["amount"] for v in school.values())

Upvotes: 4

Related Questions