Using reverse iteration to clean up a list

Paul Rubin http
Sat Mar 12 23:09:31 EST 2005


tkpmep at hotmail.com writes:
> I have list of lists of the following form
> 
> L=[['A', 100], ['B', 300], ['A', 400], ['B', -100]]
> 
> I want to aggregate these lists, i.e. to reduce L to
> L=[['A', 500], ['B', 200]] #500 = 100+400, 200=300-100

How about:

    v = {}
    for name,val in L:
      v[name] = v.get(name, 0) + val
    L = v.items()



More information about the Python-list mailing list