Dictionary removing duplicate along with subtraction and addition of values
Question: New to python here. I would like to eliminate duplicate dictionary key into
just one along with performing arithmetic such as adding/subtracting the
values if duplicates are found.

**Current Code Output**

> {('GRILLED AUSTRALIA ANGU',): (('1',), ('29.00',)), ('Beer', 'Carrot Cake',
> 'Chocolate Cake'): (('10', '1', '1'), ('30.00', '2.50', '3.50')), ('**Beer**
> ', '**Beer** '): (('**1** ', '**1** '), ('**3.00** ', '**3.00** ')),
> ('Carrot Cake', 'Chocolate Cake'): (('1', '1'), ('2.50', '3.50')), ('Carrot
> Cake',): (('1',), ('2.50',)), ('BRAISED BEANCURD WITH',): (('1',),
> ('10.00',)), ('SAUSAGE WRAPPED WITH B', 'ESCARGOT WITH GARLIC H', 'PAN
> SEARED FOIE GRAS', 'SAUTE FIELD MUSHROOM W', 'CRISPY CHICKEN WINGS', 'ONION
> RINGS'): (('1', '1', '1', '1', '1', '1'), ('10.00', '12.00', '15.00',
> '9.00', '7.00', '6.00')), ('**Beer** ', '**Beer** ', '**Carrot Cake** ',
> '**Chocolate Cake** '): (('**-1** ', '**10** ', '**1** ', '**1** '),
> ('**-3.00** ', '**30.00** ', '**2.50** ', '**3.50** ')), ('Beer',):
> (('10',), ('30.00',))}

What i want: example:

**SUBTRACTION FOR DUPLICATE**

> {'Beer': [9, 27]} , {'carrot cake': [1, 2.5]} , {'Chocolate Cake': [1, 3.5]}

notice that for duplicate item entry i trimmed Beer into one along with
(10-1=9) for quantity amount and (30-3=27) for the cost. How do i automate
this process?

**ADDITION FOR DUPLICATE**

> {'Beer': [2, 6]}

notice that I added beer and beer into one entry and along with the quantity
(1+1) and cost (3+3=6)

**My code:**

    
    
    import csv
    from itertools import groupby
    from operator import itemgetter
    import re
    
    d = {}
    
    #open directory and saving directory
    with open("rofl.csv", "rb") as f, open("out.csv", "wb") as out:
        reader = csv.reader(f)
        next(reader)
        writer = csv.writer(out)
        #the first column header
        writer.writerow(["item","quantity","amount"])
        groups = groupby(csv.reader(f), key=itemgetter(0))
    
    
        for k, v in groups:
            v = list(v)
    
    
            sales= [ x[1] for x in v[8:] ]
            salesstring= str(sales)
    
            #using re.findall instead of re.search to return all via regex for items
            itemoutput= re.findall(r"(?<=\s\s)\w+(?:\s\w+)*(?=\s\s)",textwordfortransaction)
    
            #using re.findall instead of re.search to return all via regex for amount aka quantity
            amountoutput= re.findall(r"'(-?\d+)\s+(?:[A-Za-z ]*)",textwordfortransaction)
    
            #using re.findall instead of re.search to return all via regex for cost
    
            costoutput= re.findall(r"(?:'-?\d+[A-Za-z ]*)(-?\d+[.]?\d*)",textwordfortransaction)
    
            d[tuple(itemoutput)] = tuple(amountoutput),tuple(costoutput)
    
    
            #writing the DATA to output CSV
            writer.writerow([d])
            #to remove the last entry else it would keep on stacking the previous
            d.clear()
    

link to csv file if needed
<https://drive.google.com/open?id=0B1kSBxOGO4uJOFVZSWh2NWx6dHc>


Answer: Working with your current output as posted in the question, you can just
[`zip`](https://docs.python.org/3/library/functions.html#zip) the different
lists of tuples of items and quantities and prices to align the items with
each other, add them up in two `defaultdicts`, and finally combine those to
the result.

    
    
    output = {('GRILLED AUSTRALIA ANGU',): (('1',), ('29.00',)), ...}
    
    from collections import defaultdict
    prices, quantities = defaultdict(int), defaultdict(int)
    for key, val in output.items():
        for item, quant, price in zip(key, *val):
            quantities[item] += int(quant)
            prices[item] += float(price)
    
    result = {item: (quantities[item], prices[item]) for item in prices}
    

Afterwards, `result` is this: Note that you do _not_ need a special case for
subtracting duplicates when the quantity and/or price are negative; just add
the negative number.

    
    
    {'ESCARGOT WITH GARLIC H': (1, 12.0), 
     'BRAISED BEANCURD WITH': (1, 10.0), 
     'CRISPY CHICKEN WINGS': (1, 7.0), 
     'SAUSAGE WRAPPED WITH B': (1, 10.0), 
     'ONION RINGS': (1, 6.0), 
     'PAN SEARED FOIE GRAS': (1, 15.0), 
     'Beer': (31, 93.0), 
     'Chocolate Cake': (3, 10.5), 
     'SAUTE FIELD MUSHROOM W': (1, 9.0), 
     'Carrot Cake': (4, 10.0), 
     'GRILLED AUSTRALIA ANGU': (1, 29.0)}
    

* * *

If you want to keep the individual items separate, just move the declaration
of `prices`, `quantities`, and `result` _inside_ the outer loop:

    
    
    for key, val in output.items():
        prices, quantities = defaultdict(int), defaultdict(int)
        for item, quant, price in zip(key, *val):
            quantities[item] += int(quant)
            prices[item] += float(price)
        result = {item: (quantities[item], prices[item]) for item in prices}
        # do something with result or collect in a list
    

Example result for the two-beer line:

    
    
    ('Beer', 'Beer', 'Carrot Cake', 'Chocolate Cake') (('-1', '10', '1', '1'), ('-3.00', '30.00', '2.50', '3.50'))
    {'Chocolate Cake': (1, 3.5), 'Beer': (9, 27.0), 'Carrot Cake': (1, 2.5)}
    

If you prefer the `result` to group the items, quantities and prices together,
use this:

    
    
    items = list(prices)
    result = (items, [quantities[x] for x in items], [prices[x] for x in items])
    

Result is this like this:

    
    
    (['Carrot Cake', 'Beer', 'Chocolate Cake'], [1, 9, 1], [2.5, 27.0, 3.5])
    

