Python: adding value from list of lists
Question: below is my list of lists;

    
    
    db_rows = [('a','b','c',4),
               ('a','s','f',6),
               ('a','c','d',6),
               ('a','b','f',2),
               ('a','b','c',6),
               ('a','b','f',8),
               ('a','s','f',6),
               ('a','b','f',7),
               ('a','s','f',5),
               ('a','b','f',2)]
    

if first three values are same in the inner list then I need to add 4th value
to create new list

I need result list like this:

    
    
    final_list = [('a','b','c',10),
                  ('a','s','f',17),
                  ('a','c','d',6),
                  ('a','b','f',19)]
    

I have tried the below script (not working):

    
    
    final_list = []
    for row in db_rows:
        temp_flag=False
        temp_list = []
        val = 0
        for ref_row in db_rows:
            if row != ref_row:
                if row[0]==ref_row[0] and row[1]==ref_row[1] and row[2]==ref_row[2]:
                    val = val + ref_row[3]
                    temp_flag=True
        temp_list=(row[0],row[1],row[2],val)
        if temp_flag==False:
            temp_list=row
        final_list.append(temp_list)
    

please advice me.


Answer: Use a dictionary as Dov Grobgeld commented, then convert the dictionary back
to the list.

    
    
    from collections import defaultdict
    
    db_rows = [('a','b','c',4),
               ('a','s','f',6),
               ('a','c','d',6),
               ('a','b','f',2),
               ('a','b','c',6),
               ('a','b','f',8),
               ('a','s','f',6),
               ('a','b','f',7),
               ('a','s','f',5),
               ('a','b','f',2)]
    
    sums = defaultdict(int)
    for row in db_rows:
        sums[row[:3]] += row[3]
    
    final_list = [key + (value,) for key, value in sums.iteritems()]
    

Printing `final_list` outputs:

    
    
    [('a', 'b', 'c', 10), ('a', 's', 'f', 17), ('a', 'b', 'f', 19), ('a', 'c', 'd', 6)]
    

See
[`collections.defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict).

