Sum Values in a Dictionary w/ respect to the Key - Python 2.7
Question: My dictionary `Dict` is arranged as follows. Each key is associated with a
list of values, where each value is a tuple:

    
    
    Dict = { 
        'key1': [('Red','Large',30),('Red','Medium',40),('Blue','Small',45)],
        'key2': [('Red','Large',35)],
        'key3': [('Yellow','Large',30),('Red','Medium',30)], 
    }
    

I then want to sum the integers (index 2 of each tuple) given a new key, Color
in this case.

The resulting new dictionary should look something like:

    
    
    {
        'key1': [('Red', 70), ('Blue', 45)],
        'key2': [('Red', 35)],
        'key3': [('Yellow', 30), ('Red', 30)],
    }
    

How would I accomplish this?

I was thinking something like the following, but I know this is wrong in
several ways.

    
    
    sum = 0
    new_dict = {}
    new_key = raw_input("Enter a new key to search on: ")
    for k,v in Dict:
      if v[0] == new_key:
        sum = sum + v[2]
        new_dict[k].append(sum)
      else:
        sum = 0
        new_dict[k] = [sum]
    


Answer: Use a dict comprehension to produce your new output:

    
    
    {key: [color, sum(t[2] for t in value if t[0] == color)] for key, value in Dict.iteritems()}
    

where `color` is the key to search on.

Demo:

    
    
    >>> Dict = {
    ...     'key1': [('Red','Large',30),('Red','Medium',40),('Blue','Small',45)],
    ...     'key2': [('Red','Large',35)],
    ...     'key3': [('Yellow','Large',30),('Red','Medium',30)], 
    ... }
    >>> color = 'Red'
    >>> {key: [color, sum(t[2] for t in value if t[0] == color)] for key, value in Dict.iteritems()}
    {'key3': ['Red', 30], 'key2': ['Red', 35], 'key1': ['Red', 70]}
    

To sum _all_ values by color, use a `Counter()` to sum the values:

    
    
    from collections import defaultdict, Counter
    
    new_dict = {}
    for key, values in Dict.iteritems():
        counts = Counter()
        for color, _, count in values:
            counts[color] += count
        new_dict[key] = counts.items()
    

which gives:

    
    
    >>> new_dict = {}
    >>> for key, values in Dict.iteritems():
    ...     counts = Counter()
    ...     for color, _, count in values:
    ...         counts[color] += count
    ...     new_dict[key] = counts.items()
    ... 
    >>> new_dict
    {'key3': [('Red', 30), ('Yellow', 30)], 'key2': [('Red', 35)], 'key1': [('Blue', 45), ('Red', 70)]}
    

