the dictionary data look like this
JavaScript
x
7
1
[
2
{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 30},
3
{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 40},
4
{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 20},
5
{'br' : 'Dede', 'mnt' : '2020-5', 'vl' : 20},
6
{'br' : 'Dede', 'mnt' : '2020-5', 'vl' : 40},]
7
and the result is sum vl if only br and mnt have same value
JavaScript
1
5
1
[
2
{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 90},
3
{'br' : 'Dede', 'mnt' : '2020-5', 'vl' : 60}
4
]
5
Advertisement
Answer
If you can use pandas
, try this:
JavaScript
1
13
13
1
import pandas as pd
2
data = [{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 30},
3
{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 40},
4
{'br' : 'Kadek', 'mnt' : '2020-10', 'vl' : 20},
5
{'br' : 'Dede', 'mnt' : '2020-5', 'vl' : 20},
6
{'br' : 'Dede', 'mnt' : '2020-5', 'vl' : 40}]
7
8
# turn data into a pandas dataframe
9
df = pd.DataFrame(data)
10
# take the sum when br and mnt are the same
11
df_grouped = df.groupby(['br','mnt']).agg({'vl':'sum'}).reset_index()
12
df_grouped
13
This outputs:
JavaScript
1
5
1
br mnt vl
2
0 Dede 2020-5 60
3
1 Kadek 2020-10 90
4
5
If you really need to, you can turn it back into a list of dictionaries with:
JavaScript
1
2
1
df_grouped.to_dict('records')
2