Python | Sum values for each key in nested dictionary

Python | Sum values for each key in nested dictionary

To sum values for each key in a nested dictionary, you can iterate over the outer dictionary and then sum the values of the inner dictionaries. Let's see how this can be done.

Given a nested dictionary like this:

data = { 'A': {'x': 5, 'y': 10, 'z': 15}, 'B': {'x': 15, 'y': 20, 'z': 25}, 'C': {'x': 25, 'y': 30, 'z': 35} } 

You want to obtain a result like:

{ 'x': 45, 'y': 60, 'z': 75 } 

Here's a code snippet to achieve that:

data = { 'A': {'x': 5, 'y': 10, 'z': 15}, 'B': {'x': 15, 'y': 20, 'z': 25}, 'C': {'x': 25, 'y': 30, 'z': 35} } result = {} for key, subdict in data.items(): for subkey, value in subdict.items(): result[subkey] = result.get(subkey, 0) + value print(result) 

The code uses the get() method to retrieve the current sum for a subkey or default to 0 if the subkey doesn't exist in the result dictionary yet. It then adds the value to that sum.


More Tags

pdfminer file-sharing transactional mamp asp.net-core-webapi php-shorttags window.location formarray docker-desktop secret-key

More Programming Guides

Other Guides

More Programming Examples