2

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}
]

2 Answers 2

3

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')
Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot @Kris, I also resolve it by Counter from collections import Counter
1
from collections import Counter 

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},]

cnt = Counter()

for i in data:
    cnt[i['br'], i['mnt']] += i['value']

result = ([{'br': k[0], 'mnt': k[1], 'value': v}
        for k, v in cnt.items()])

print(result)

output:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.