Python - Summing a list of dictionaries with a condition
Question: Let say I have a list:

    
    
    l = [{"num1":3, "num2":8, "num3":5, "type":"A"}, {"num1":2, "num2":5, "num3":5, "type":"B"}, {"num1":5, "num2":2, "num3":1, "type":"A"}, {"num1":4, "num2":4, "num3":9, "type":"B"}
    

and I want to create 2 dictionaries: sumA:

    
    
    {"num1":8, "num2":10, "num3":6}
    

sumB:

    
    
    {"num1":6, "num2":9, "num3":14}
    

I want to make it simple and readable as much as possible. I managed to do it
in a horrible way using too many variables...

Thanks!


Answer: This can be done reasonably easily using some [list and dict
comprehensions](http://www.youtube.com/watch?v=pShL9DCSIUw).

    
    
    from operator import itemgetter
    from itertools import groupby
    
    l = [{"num1": 3, "num2": 8, "num3": 5, "type": "A"},
         {"num1": 2, "num2": 5, "num3": 5, "type": "B"},
         {"num1": 5, "num2": 2, "num3": 1, "type": "A"},
         {"num1": 4, "num2": 4, "num3": 9, "type": "B"}]
    
    wanted_values = {"num1", "num2", "num3"}
    
    type_getter = itemgetter("type")
    groups = [(group, list(items)) for group, items in 
              groupby(sorted(l, key=type_getter), type_getter)]
    
    print({group: {k: sum(map(itemgetter(k), items)) for k in wanted_values}
           for group, items in groups})
    

Which gives us:

    
    
    {'B': {'num2': 9, 'num3': 14, 'num1': 6}, 
     'A': {'num2': 10, 'num3': 6, 'num1': 8}}
    

We sort the values by type, then split them into groups with
[`itertools.groupby()`](http://docs.python.org/3.3/library/itertools.html#itertools.groupby)
(making the items lists instead of generators, as we need to iterate over them
multiple times).

We then use a nested dict comprehension to create the data we need, summing
the values from the items and assigning them to a group.

This is a flexible solution that would scale to having more than just two
types.

