Search code examples
pythonpython-3.xpymysql

How to sum all the values that belong to the same key?


I'm pulling data from the database and assuming i have something like this:

    Product Name    Quantity
    a               3
    a               5
    b               2
    c               7

I want to sum the Quantity based on Product name, so this is what i want:

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

Here's what I'm trying to do after fetching the data from the database:

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

but this will give me: 'a'=5 only, not 8.


Solution

  • If you insist on using loops, you can do this:

    # 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))
    

    The output:

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