用一个键将多个键的字典相加的最有效方法是什么? [英] What is the most efficient way to sum a dict with multiple keys by one key?

查看:100
本文介绍了用一个键将多个键的字典相加的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下dict结构.

I have the following dict structure.

product1 = {'product_tmpl_id': product_id,
'qty':product_uom_qty,
'price':price_unit,
'subtotal':price_subtotal,
'total':price_total,
}

然后是产品列表,列表中的每个项目都是具有上述结构的字典

And then a list of products, each item in the list is a dict with the above structure

list_ = [product1,product2,product3,.....]

我需要对列表中的项求和,按键product_tmpl_id分组...我正在使用dictcollections,但它仅求和qty键,我需要对键求和,除了product_tmpl_id这是标准分组

I need to sum the item in the list, group by the key product_tmpl_id ... I'm using dictcollections but it only sum the qty key, I need to sum key except the product_tmpl_id which is the criteria to group by

c = defaultdict(float)
for d in list_:
    c[d['product_tmpl_id']] += d['qty']
c = [{'product_id': id, 'qty': qty} for id, qty in c.items()]

我知道如何使用for迭代来实现,但是试图寻找一种更加Python化的方式

I know how to do it with a for iteration but trying to look for a more pythonic way

谢谢

需要通过的是这一点:

lst = [
{'Name': 'A', 'qty':100,'price':10},
{'Name': 'A', 'qty':100,'price':10},
{'Name': 'A', 'qty':100,'price':10},
{'Name': 'B', 'qty':100,'price':10},
{'Name': 'C', 'qty':100,'price':10},
{'Name': 'C', 'qty':100,'price':10},
]

对此

group_lst = [
{'Name': 'A', 'qty':300,'price':30},
{'Name': 'B', 'qty':100,'price':10},
{'Name': 'C', 'qty':200,'price':20},
]

推荐答案

使用基本的Python并不会带来很多好处.您可以与itertools.groupby一起破解某些东西,但这很丑陋,而且速度可能较慢,当然还不太清楚.

Using basic Python, this doesn't get a whole lot better. You could hack something together with itertools.groupby, but it'd be ugly and probably slower, certainly less clear.

不过,正如@ 9769953所建议的那样,Pandas是处理此类结构化表格数据的好软件包.

As @9769953 suggested, though, Pandas is a good package to handle this sort of structured, tabular data.

In [1]: import pandas as pd
In [2]: df = pd.DataFrame(lst)
Out[2]:
  Name  price  qty
0    A     10  100
1    A     10  100
2    A     10  100
3    B     10  100
4    C     10  100
5    C     10  100
In [3]: df.groupby('Name').agg(sum)
Out[3]:
      price  qty
Name
A        30  300
B        10  100
C        20  200

如果您不想将数据保留为数据帧,则只需要一点额外的mojo:

You just need a little extra mojo if you don't want to keep the data as a dataframe:

In [4]: grouped = df.groupby('Name', as_index=False).agg(sum)
In [5]: list(grouped.T.to_dict().values())
Out[5]:
[{'Name': 'A', 'price': 30, 'qty': 300},
 {'Name': 'B', 'price': 10, 'qty': 100},
 {'Name': 'C', 'price': 20, 'qty': 200}]

这篇关于用一个键将多个键的字典相加的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆