I searched for some time, but couldn't find an exact solution to my problem. I have a list of dictionaries in format:
d = [{"sender": "a", "time": 123, "receiver": "b", "amount": 2}, {"sender": "c", "time": 124, "receiver": "b", "amount": 10}, {"sender": "a", "time": 130, "receiver": "b", "amount": 5}]
I would like to find the best way to iterate over all the dictionaries and count how many times a given pair of sender-receiver occurs and the sum of the total amount.
So I would like to get:
result = [{"sender": "a", "receiver":b, "count": 2, "total_amount":7}, {"sender": "c", "receiver":b, "count": 1, "total_amount":10}]
I am pretty sure I can probably make this work by iterating over all the dictionaries in the list one by one, saving the information in a temporary dictionary, but that will lead to a lot of nested if loops. I was hoping there is a cleaner way to do this.
I know I can use Counter to count the number of occurences for a unique value:
from collections import Counter
Counter(val["sender"] for val in d)
which will give me:
>>> ({"a":2, "c":1})
but how can I do this for a pair of values and have separate dictionaries for each?
Thank you in advance and I hope my question was clear enough