Iterate python list and sum equal items
Question: Considering a endpoint on my backend, that returns the following response:

    
    
    class Arc_Edges_Data(Resource):
      def get(self):
            #Connect to databse
            conn = connectDB()
            cur = conn.cursor()
            #Perform query and return JSON data
            try:
              cur.execute("select json_build_object('source', start_location, 'target', end_location, 'frequency', 1) from trips")
            except:
              print("Error executing select")
            ArcList = list (i[0] for i in cur.fetchall())
            return ArcList
    

The frequency here is supposed to be always of 1 for each trip. So this
`ArcList` originates a response like this:

    
    
    [
        {
            "frequency": 1, 
            "source": "c", 
            "target": "c"
        }, 
        {
            "frequency": 1, 
            "source": "a", 
            "target": "b"
        }, {
            "frequency": 1, 
            "source": "a", 
            "target": "b"
        }, ...
    ]
    

How can I iterate this response and sum the items that have the same `source`
and `target`? In this case, the resulting list would have only one pair
source/target with "a" and "b", but the frequency would be 2, because of the
sum.

I know that for Javascript I could use something like `Array.reduce`, but I
don't think it exists for Python.


Answer: How about this?

    
    
    import collections
    
    data = [
        {
            "frequency": 1, 
            "source": "c", 
            "target": "c",
        }, 
        {
            "frequency": 1, 
            "source": "a", 
            "target": "b",
        },
        {
            "frequency": 1, 
            "source": "a", 
            "target": "b",
        },
    ]
    
    counter = collections.Counter()
    
    for datum in data:
        counter[(datum['source'], datum['target'])] += datum['frequency']
    
    print(counter)
    
    # Output:
    # Counter({('a', 'b'): 2, ('c', 'c'): 1})
    

Oh, if you want to put the data back into the same format again, add this
code:

    
    
    newdata = [{
        'source': k[0],
        'target': k[1],
        'frequency': v,
    } for k, v in counter.items()]
    
    print(newdata)
    
    # Output:
    # [{'frequency': 1, 'target': 'c', 'source': 'c'}, {'frequency': 2, 'target': 'b', 'source': 'a'}]
    

