Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

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}
]
question from:https://stackoverflow.com/questions/65901401/how-can-i-sum-value-from-array-in-dictionary-with-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...