How to remove a repeated dictionary in a list of dictionaries?
Question: I have a list in Python:

    
    
    [{u'key': u'Central District', u'doc_count': 21468},
     {u'key': u'Central District', u'doc_count': 6190},
     {u'key': u'Central District', u'doc_count': 2060},
     {u'key': u'Mexico', u'doc_count': 1884}]
    

but I need to turn it into this:

    
    
    [{u'key': u'Central District', u'doc_count':  29718},
     {u'key': u'Mexico', u'doc_count': 1884}]
    

How can I eliminate one of the repeated elements (in this case "Central
District"), and get the sum of the `doc_count` values of each "Central
District"?


Answer: Itertools and reduce can help sum the values grouped by key.

    
    
    from itertools import groupby
    
    original = [{u'key': u'Central District', u'doc_count': 21468},
                {u'key': u'Central District', u'doc_count': 6190},
                {u'key': u'Central District', u'doc_count': 2060},
                {u'key': u'Mexico', u'doc_count': 1884}]
    
    def sum_reduce(obj1, obj2):
        return {'key': obj1['key'], 'doc_count': obj1['doc_count'] + obj2['doc_count']}
    
    combined = [reduce(sum_reduce, group) for _, group in groupby(original, lambda x: x['key'])]
    
    print combined 
    # output: 
    # [{'key': u'Central District', 'doc_count': 29718}, {u'key': u'Mexico',  u'doc_count': 1884}]
    

