简体   繁体   English

在不使用Counter的情况下合并python字典中的值

[英]Combining values in python dictionaries without using Counter

I am trying to write this program without using Counter.Write a Python program to combine values in python list of dictionaries. 我正在尝试不使用Counter编写此程序。编写一个Python程序来组合python字典列表中的值。 Go to the editor Sample data: 转到编辑器样本数据:

[{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1', 'amount': 750}]
**Expected Output: {'item1': 1150, 'item2': 300}**

So far here's my code. 到目前为止,这是我的代码。

a=[{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1', 'amount': 750}]    
cp={}
val=0
for d in a:
    if d['item'] not in cp:
        cp[d['item']]=d['amount']
print(cp)   

My output: {'item1': 400, 'item2': 300} 我的输出: {'item1': 400, 'item2': 300}

How can I combined the total of of 'item1'?Any help is appreciated? 如何合并'item1'的总和?有帮助吗?

a=[{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1', 'amount': 750}]    
cp={}
val=0
for d in a:
    if d['item'] not in cp:
        cp[d['item']] = d['amount']
    else:
        cp[d['item']] += d['amount'] 
print(cp) 

Here is one way: 这是一种方法:

from collections import defaultdict

lst = [{'item': 'item1', 'amount': 400},
       {'item': 'item2', 'amount': 300},
       {'item': 'item1', 'amount': 750}]

d = defaultdict(int)

for i in lst:
    d[i['item']] += i['amount']

# defaultdict(<class 'int'>, {'item1': 1150, 'item2': 300})
d = {}
for a_dict in all_my_dicts:
    for key in a_dict:
       d[key] = d.get(key,0)+a_dict[key]

I guess maybe 我想也许

You can use defaultdict here. 您可以在此处使用defaultdict

from collections import defaultdict
for d in l:
    data[d['item']] += d['amount']

Out[72]: defaultdict(int, {'item1': 1150, 'item2': 300})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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