Reputation: 11
I have the following nested dictionary and need to figure out how to sum all 'qty'.
data1 = {
'Batch1': {
'Pink': {'qty': 25, 'ordered': 15},
'Blue': {'qty': 18, 'ordered': 20}
},
'Batch2': {
'Coke': {'qty': 50, 'ordered': 100},
'Sprite': {'qty': 30, 'ordered': 25}
}
}
So the outcomes would be 123.
Upvotes: 1
Views: 88
Reputation: 50185
Your data1
was formatted funny, so here's what I used:
{'Batch1': {'Blue': {'ordered': 20, 'qty': 18},
'Pink': {'ordered': 15, 'qty': 25}},
'Batch2': {'Coke': {'ordered': 100, 'qty': 50},
'Sprite': {'ordered': 25, 'qty': 30}}}
If you're not sure how deeply nested your dict will be, you can write a function to recursively traverse the nested dict looking for the qty
key and sum the values:
def find_key_vals(query_key, base_dict):
values = []
for k, v in base_dict.items():
if k == query_key:
values.append(v)
elif isinstance(v, dict):
values += find_key_vals(query_key, v)
return values
find_key_vals('qty', data1)
# => [50, 30, 25, 18]
sum(find_key_vals('qty', data1))
# => 123
Upvotes: 0
Reputation: 71451
You can use sum
:
data1 = {'Batch1': {'Pink': {'qty': 25, 'ordered':15}, 'Blue': {'qty':18, 'ordered':20}}, 'Batch2': {'Coke': {'qty': 50, 'ordered': 100},'Sprite': {'qty':30, 'ordered':25}}}
result = sum(b['qty'] for c in data1.values() for b in c.values())
Output:
123
Upvotes: 4