Home > Back-end >  Add all duplicate values from list of dictionaries
Add all duplicate values from list of dictionaries

Time:09-08

I have a list of dictionaries:

foo = [{'date':'01-08-2022', 'pre_val':90, 'cur_val':100},{'date':'02-08-2022', 'pre_val':70, 'cur_val':100},{'date':'01-08-2022', 'pre_val':60, 'cur_val':50}]

I would like to add all the duplicate day's values

bar = [{'date':'01-08-2022', 'pre_val':150, 'cur_val':150},{'date':'02-08-2022', 'pre_val':70, 'cur_val':100}]

Can anyone help me with this?

CodePudding user response:

This can be very easily done using pandas grouping operations:

import pandas as pd
data = [{'date':'01-08-2022', 'pre_val':90, 'cur_val':100},{'date':'02-08-2022', 'pre_val':70, 'cur_val':100},{'date':'01-08-2022', 'pre_val':60, 'cur_val':50}]
df = pd.DataFrame(data)
>>          date  pre_val  cur_val
>> 0  01-08-2022       90      100
>> 1  02-08-2022       70      100
>> 2  01-08-2022       60       50

df2 = df.groupby("date") \
  .agg( \
       pre_val=("pre_val", sum), \
       cur_val=("cur_val", sum), \
      ) \
  .reset_index()
>>          date  pre_val  cur_val
>> 0  01-08-2022      150      150
>> 1  02-08-2022       70      100

df2.set_index("date").T.to_dict()
>> {'01-08-2022': {'pre_val': 150, 'cur_val': 150}, '02-08-2022': {'pre_val': 70, 'cur_val': 100}}

CodePudding user response:

foo = [{'date':'01-08-2022', 'pre_val':90, 'cur_val':100},
    {'date':'02-08-2022', 'pre_val':70, 'cur_val':100},
    {'date':'01-08-2022', 'pre_val':60, 'cur_val':50}]
bar = []
for i in foo:
    date, pre_val, cur_val = i.values()
    isupdate = False
    for d in bar:
        if d["date"] == date:
            d1 = {'pre_val':d["pre_val"]   pre_val, 
                'cur_val':d["cur_val"]   cur_val}
            d.update(d1)
            isupdate = True
    if not isupdate:
        bar.append(i)

Output:

[{'date': '01-08-2022', 'pre_val': 150, 'cur_val': 150}, {'date': '02-08-2022', 'pre_val': 70, 'cur_val': 100}]
  • Related