Python 如何对属于同一个键的所有值求和?

Python 如何对属于同一个键的所有值求和?,python,python-3.x,pymysql,Python,Python 3.x,Pymysql,我正在从数据库中提取数据,并假设我有如下内容: Product Name Quantity a 3 a 5 b 2 c 7 我想根据产品名称对数量求和,所以这就是我想要的: product = {'a':8, 'b':2, 'c':7 } 从数据库中获取数据后,我将尝试执行以下操作: for row in result:

我正在从数据库中提取数据,并假设我有如下内容:

    Product Name    Quantity
    a               3
    a               5
    b               2
    c               7
我想根据产品名称对数量求和,所以这就是我想要的:

    product = {'a':8, 'b':2, 'c':7 }
从数据库中获取数据后,我将尝试执行以下操作:

    for row in result:
       product[row['product_name']] += row['quantity']

但这将给我:a'=5,而不是8。选项1:熊猫

这是一种方法,假设您以
pandas
dataframe
df
开始。此解决方案具有O(n logn)复杂性

product = df.groupby('Product Name')['Quantity'].sum().to_dict()

# {'a': 8, 'b': 2, 'c': 7}
from collections import Counter

result = [['a', 3],
          ['a', 5],
          ['b', 2],
          ['c', 7]]

product = Counter()

for row in result:
    product[row[0]] += row[1]

print(product)
# Counter({'a': 8, 'c': 7, 'b': 2})
其思想是您可以执行
groupby
操作,该操作将生成一个按“产品名称”索引的系列。然后使用
to_dict()
方法转换为字典

选项2:集合。计数器

如果您从结果列表或迭代器开始,并希望对循环使用
,则可以对O(n)复杂度使用
集合.计数器

product = df.groupby('Product Name')['Quantity'].sum().to_dict()

# {'a': 8, 'b': 2, 'c': 7}
from collections import Counter

result = [['a', 3],
          ['a', 5],
          ['b', 2],
          ['c', 7]]

product = Counter()

for row in result:
    product[row[0]] += row[1]

print(product)
# Counter({'a': 8, 'c': 7, 'b': 2})
选项3:itertools.groupby

您还可以将字典理解与
itertools.groupby
一起使用。这需要事先分类

from itertools import groupby

res = {i: sum(list(zip(*j))[1]) for i, j in groupby(sorted(result), key=lambda x: x[0])}

# {'a': 8, 'b': 2, 'c': 7}

如果您坚持使用循环,您可以这样做:

# fake data to make the script runnable
result = [
  {'product_name': 'a', 'quantity': 3},
  {'product_name': 'a', 'quantity': 5},
  {'product_name': 'b', 'quantity': 2},
  {'product_name': 'c', 'quantity': 7}
]

# solution with defaultdict and loops
from collections import defaultdict

d = defaultdict(int)
for row in result:
  d[row['product_name']] += row['quantity']

print(dict(d))
输出:

{'a': 8, 'b': 2, 'c': 7}

使用
tuple
存储结果

编辑:


不清楚提到的数据是否真的是数据帧

如果是,则
li=[df.to_记录中x的元组(x)(index=False)]


输出
自从你提到熊猫

df.set_index('ProductName').Quantity.sum(level=0).to_dict()
Out[20]: {'a': 8, 'b': 2, 'c': 7}

如果产品按某个键而不是按
'product\u name'
排序,则
groupby会发生什么情况?
pandas.DataFrame.groupby
不需要事先进行显式排序。这是在后台发生的。这就是为什么它是O(n log n)解决方案而不是集合。计数器O(n)解决方案。感谢您提供的信息,学到了一些新的东西!我发现列表上的
groupby
的行为有些令人惊讶。@Andreytukin,是的-不应该将数据帧上的panda
groupby
与列表上的itertools
groupby
混淆起来。
itertools
方法首先需要显式排序。我认为OP不会轻易影响查询返回数据的格式。
int(str(…)
有什么用?我认为dunder
\uuuu包含的
不应该被显式调用,而是使用d
中的
x。此外,看看其他答案:一个是使用
defaultdict
,另一个是使用
计数器。两个版本似乎都略显简洁。