Skip to content
Advertisement

How can I sum value from array in dictionary with python?

the dictionary data look like this

[
{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 30},
{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 40},
{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 20},
{'br' : 'Dede', 'mnt' : '2020-5', 'vl' : 20},
{'br' : 'Dede', 'mnt' : '2020-5', 'vl' : 40},]

and the result is sum vl if only br and mnt have same value

[
{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 90},
{'br' : 'Dede', 'mnt' : '2020-5', 'vl' : 60}
]

Advertisement

Answer

If you can use pandas, try this:

import pandas as pd 
data = [{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 30},
{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 40},
{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 20},
{'br' : 'Dede', 'mnt' : '2020-5', 'vl' : 20},
{'br' : 'Dede', 'mnt' : '2020-5', 'vl' : 40}]

# turn data into a pandas dataframe
df = pd.DataFrame(data)
# take the sum when br and mnt are the same
df_grouped = df.groupby(['br','mnt']).agg({'vl':'sum'}).reset_index()
df_grouped

This outputs:

    br      mnt     vl
0   Dede    2020-5  60
1   Kadek   2020-10 90

If you really need to, you can turn it back into a list of dictionaries with:

df_grouped.to_dict('records')
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement