I have a dict as below:
dict_data = {
"NAME": ['A', 'B', 'A', 'B', 'C', 'C'],
"VALUE": [100, 200 , 100 , 200, 300, 300]
}
How to sum values from above dict if NAME duplicate output:
NAME: A
VALUE: 200
NAME: B
VALUE: 400
NAME: C
VALUE: 600
or output to with list:
[A, B, C]
[200, 400, 600]
CodePudding user response:
Use a collections.defaultdict
then iterate and sum by grouping on key
dict_data = {"NAME": ["A", "B", "A", "B", "C", "C"], "VALUE": [100, 200, 100, 200, 300, 300]}
from collections import defaultdict
result = defaultdict(int)
for key, value in zip(dict_data['NAME'], dict_data['VALUE']):
result[key] = value
for key, value in result.items():
print("NAME", key)
print("VALUE", value)
keys, values = zip(*result.items())
print(keys)
print(values)
NAME A
VALUE 200
NAME B
VALUE 400
NAME C
VALUE 600
('A', 'B', 'C')
(200, 400, 600)
CodePudding user response:
You can use defaultdict
with zero
in start.
dict_data = {
"NAME": ['A', 'B', 'A' , 'B' , 'C' , 'C'],
"VALUE": [100, 200 , 100 , 200, 300, 300]
}
from collections import defaultdict
# res = defaultdict(lambda : 0)
res = defaultdict(int)
for k,v in zip(dict_data['NAME'], dict_data['VALUE']):
res[k] = v
print(list(res.keys()))
print(list(res.values()))
Output:
['A', 'B', 'C']
[200, 400, 600]
CodePudding user response:
Without extra imports.
Use class method fromkeys
to set default values
d = dict.fromkeys(dict_data['NAME'], 0)
for k, v in zip(dict_data['NAME'], dict_data['VALUE']):
d[k] = v
print(d)
or, more verbosely, with the instance method setdefault
d = {}
for k, v in zip(dict_data['NAME'], dict_data['VALUE']):
d.setdefault(k, 0)
d[k] = v
These solutions are meant to reply to the comment "If you don't use defualtdict, you can not wtite res[k] = v
"