Sum the values of dictionaries inside a list where the keys are the same
IIUC this is pretty straight forward. You just write a function to sum up all values per key. Then apply it to the transposed list of lists of dicts.
def sum_by_key(dicts):
result = {}
for d in dicts:
for k, v in d.items():
result[k] = result.get(k, 0) + v
return result
lists_of_dicts = [[{1:2, 3:4}, {1:10, 2:9}], [{3:8, 2:4}, {3:1, 2:5}]]
result = [sum_by_key(dicts) for dicts in zip(*lists_of_dicts)]
print(result)
(lists_of_dicts
would be [A, B, C, D]
with your variables)
Output:
[{1: 2, 3: 12, 2: 4}, {1: 10, 2: 14, 3: 1}]
edit: with your new sample data
lists_of_dicts = [A, B, C, D]
result = [sum_by_key(dicts) for dicts in zip(*lists_of_dicts)]
print(result)
produces
[{'1': 1158, '2': 1450, '3': 542, '4': 2060}, {'1': 702, '2': 2600, '3': 1169, '4': 1670}, {'1': 880, '2': 2480, '3': 2000, '4': 3852}, {'1': 600, '2': 640, '3': 1142, '4': 6230}]
Python - Sum the value in the list of dictionary based on the same key
Your data is rather a DataFrame, a natural pandas
solution is :
In [34]: pd.DataFrame.from_records(data).astype(int).groupby('player').sum().T.to_dict()
Out[34]: {1: {'stat2': 5, 'stat3': 13}, 3: {'stat2': 8, 'stat3': 9}}
Sum values of duplicate(common) keys in a list of dictionary
Following up on @python_user's comment
Here is how you implement the solution for your code
tax = [{'taxType': 'T1', 'amount': 140},{'taxType': 'T1', 'amount': 10}]
aggregated_data = {}
for dictionary in tax:
key = (dictionary['taxType'])
aggregated_data[key] = aggregated_data.get(key, 0) + dictionary['amount']
tax = [{'taxType': key, 'amount': value} for key, value in aggregated_data.items()]
print(tax)
output
[{'taxType': 'T1', 'amount': 150}]
How to sum elements in list of dictionaries if two key values are the same
This is possible, but non-trivial to implement in python. Might I suggest using pandas? This is simple with a groupby
, sum
, and to_dict
.
import pandas as pd
(pd.DataFrame(dictionary)
.groupby(['Location', 'Name'], as_index=False)
.Flow.sum()
.to_dict('r'))
[{'Flow': 160, 'Location': 'Europe', 'Name': 'B1'},
{'Flow': 120, 'Location': 'USA', 'Name': 'A1'}]
To install, use pip install --user pandas
.
Otherwise, you can apply a pseudo-generic group operation using itertools.groupby
.
from itertools import groupby
from operator import itemgetter
grouper = ['Location', 'Name']
key = itemgetter(*grouper)
dictionary.sort(key=key)
[{**dict(zip(grouper, k)), 'Flow': sum(map(itemgetter('Flow'), g))}
for k, g in groupby(dictionary, key=key)]
[{'Flow': 160, 'Location': 'Europe', 'Name': 'B1'},
{'Flow': 120, 'Location': 'USA', 'Name': 'A1'}]
Add up values of same key in a nested dictionary
If you wish to store your result in a dictionary, you can create one with the keys from your list and calculate the results there.
result = {i: 0 for i in mylist}
for k, v in d.items():
result['age'] += v['age']
result['answ1'] += v['answ1']
result['answ2'] += v['answ2']
result['answ3'] += v['answ3']
result
{'age': 71, 'answ1': 11, 'answ2': 8, 'answ3': 12}
However this does rely on the keys not changing, order should not matter.
EDIT
You can do this regardless of key names with the following update. Note it adds one extra iteration.
result = {i: 0 for i in mylist}
for k, v in d.items():
for ke, va in v.items():
result[ke] += v[ke]
How sum dict element by same key value
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)
Merge lists of dictionaries by summing values of the same key
Try this if you want to sum all values for unique 'name'
in each dictionaries :
names = set([k['name'] for k in dict1+dict2])
dict3 = []
for name in names:
temp_val = []
for dict_ in dict1+dict2:
if dict_['name'] == name:
temp_val.append(dict_['value'])
dict3.append({'name': name, 'value' : sum(temp_val)})
OUTPUT :
[{'name': 'A', 'value': 16}, {'name': 'B', 'value': 5}, {'name': 'C', 'value': 12}]
How to sum up values of duplicate keys in a dictionary?
You need to check for key existence first. If the key already exists, you add the value directly rather than call the Add()
method.
var mydic = new Dictionary<string, int>();
for (int i = 0; i < keys.Count; i++)
{
if(mydic.ContainsKey(keys[i]))
mydic[keys[i]] += values[i];
else
mydic.Add(keys[i], values[i]);
}
Python3: get sum of values of specific key in list of dictionary
Pandas to the rescue!
First, create a dataframe from your data
df = pd.DataFrame(data)
print(df)
Output:
id value
0 1 3
1 2 1
2 3 5
3 1 1
4 1 2
5 3 2
6 1 3
Then, group by id and sum
result = df.groupby("id").sum()
print(result)
Output:
value
id
1 9
2 1
3 7
And then convert this to the list like you want:
new_list = [{"id": elemid, "value": val.value} for elemid, val in result.iterrows()]
print(new_list)
# Output: [{'id': 1, 'value': 9}, {'id': 2, 'value': 1}, {'id': 3, 'value': 7}]
Alternatively, you could just improve your existing way:
data = [
{"id": 1, "value": 3},
{"id": 2, "value": 1},
{"id": 3, "value": 5},
{"id": 1, "value": 1},
{"id": 1, "value": 2},
{"id": 3, "value": 2},
{"id": 1, "value": 3}
]
new_data = {}
for elem in data:
elemid = elem["id"]
value = elem["value"]
new_data[elemid] = new_data.get(elemid, 0) + value
print(new_data)
# Output: {1: 9, 2: 1, 3: 7}
Then, convert this to the list like you want:
new_list = [{"id": key, "value": value} for key, value in new_data.items()]
print(new_list)
# Output: [{'id': 1, 'value': 9}, {'id': 2, 'value': 1}, {'id': 3, 'value': 7}]
Related Topics
Keep Other Columns When Doing Groupby
Pyspark Add New Row to Dataframe
What Is the Simplest Way to Ssh Using Python
How to Get the Column Name in Pandas Based on Row Values
How to Sort the Letters in a String Alphabetically in Python
Regular Expression to Check Whitespace in the Beginning and End of a String
How to Get Text from Span Tag in Beautifulsoup
How to Execute Two Commands in Terminal Using Python'S Subprocess Module
Tkinter: How to Use Threads to Preventing Main Event Loop from "Freezing"
Comparing Two Json Objects Irrespective of the Sequence of Elements in Them
Print Floating Point Values Without Leading Zero
Plot Different Dataframes in the Same Figure
How to Clear or Overwrite a Tkinter Canvas
Pyspark Regexp_Replace With List Elements Are Not Replacing the String
How to Sort a Single String Output in Ascii Descending Order Through a Function