简体   繁体   中英

How sum dict element by same key value

There is a list of dictionaries:

list_dict = [
    {
        "id_sistema_productivo": 48,
        "area": 327
    },
    {
        "id_sistema_productivo": 51,
        "area": 205.65
    },
    {
        "id_sistema_productivo": 48,
        "area": 327
    },
    {
        "id_sistema_productivo": 51,
        "area": 209.13
    }
]

I don't think I'm getting it quite right (been stuck for hours), but the expected response should look like this:

new_list_dict = [
    {
        "id_sistema_productivo": 48,
        "area": 654
    },
    {
        "id_sistema_productivo": 51,
        "area": 414.78
    },
]

All your dictionaries have the same keys, you can first sum each of them using a default dict, then reconstructing a list from the results:

from collections import defaultdict
 
result = defaultdict(int)
for d in list_dict:
  result[d["id_sistema_productivo"]] += d["area"]

result = [{"id_sistema_productivo": id, "area": area} for id, area in result.items()]

If the dictionary keys are always the same, consider encapsulating it in a class, it will be clearer (example using dataclass which is really convenient):

from dataclasses import dataclass

@dataclass
class Element:
    id_sistema_productivo: int
    area: int

you can then express what you want more easily:

list_dict = [
  Element(48, 327),
  Element(51, 205.65),
  Element(48, 327),
  Element(51, 209.13)
]

result = defaultdict(int)
for element in list_dict:
    result[element.id_sistema_productivo] += element.area
result = [Element(i, a) for i, a in result.items()]

print(result)

you can do that with pandas :

import pandas as pd
list_dict = [
  {
    "id_sistema_productivo": 48,
    "area": 327
  },
  {
    "id_sistema_productivo": 51,
    "area": 205.65
  },
  {
    "id_sistema_productivo": 48,
    "area": 327
  },
  {
    "id_sistema_productivo": 51,
    "area": 209.13
  }
]
df=pd.DataFrame(list_dict)
data=df.groupby(['id_sistema_productivo']).sum()
print(data)

Assuming the same predictability of input as Louis

list_of_dicts = [                                                                                                                                                                                                  
  {
    "id_sistema_productivo": 48, 
    "area": 327 
  },  
  {
    "id_sistema_productivo": 51, 
    "area": 205.65
  },  
  {
    "id_sistema_productivo": 48, 
    "area": 327 
  },  
  {
    "id_sistema_productivo": 51, 
    "area": 209.13
  }
]

from collections import Counter
c = Counter()
[c.update({d["id_sistema_productivo"]: d["area"]}) for d in list_of_dicts]
result = [{"id_sistema_produtivo":k, "area":v} for k,v in c.items()]
print(result)

Gives the output

[{'id_sistema_produtivo': 48, 'area': 654}, {'id_sistema_produtivo': 51, 'area': 414.78}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM