Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum values in a list of lists of dictionaries using common key-value pairs

How do I sum duplicate elements in a list of lists of dictionaries?

Sample list:

data = [
        [
            {'user': 1, 'rating': 0},
            {'user': 2, 'rating': 10},
            {'user': 1, 'rating': 20},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 20},
            {'user': 1, 'rating': 10}
        ],
    ]

Expected output:

op = [
        [
            {'user': 1, 'rating': 20},
            {'user': 2, 'rating': 10},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 30},
        ],
    ]
like image 272
rahul.m Avatar asked May 30 '20 12:05

rahul.m


People also ask

How do you sum the values of each key in a Python dictionary?

Practical Data Science using Python It is pretty easy to get the sum of values of a python dictionary. You can first get the values in a list using the dict. values(). Then you can call the sum method to get the sum of these values.

How do you sum a list of values in a dictionary?

To sum the values in a list of dictionaries: Use a generator expression to iterate over the list. On each iteration, access the current dictionary at the specific key. Pass the generator expression to the sum() function.

Can you use sum () for calculating the sum of the values of a dictionary?

Using sum() function A simple solution is to use the built-in function sum() to calculate the sum of all the dictionary's values. The idea is to get a view of the dictionary's values using the dict. values() function and pass it to sum() . You can also achieve this with a list comprehension.


1 Answers

With pandas:

>>> import pandas as pd
>>> [pd.DataFrame(dicts).groupby('user', as_index=False, sort=False).sum().to_dict(orient='records') for dicts in data]
[[{'user': 1, 'rating': 20},
  {'user': 2, 'rating': 10},
  {'user': 3, 'rating': 10}],
 [{'user': 4, 'rating': 4},
  {'user': 2, 'rating': 80},
  {'user': 1, 'rating': 30}]]
like image 110
timgeb Avatar answered Sep 28 '22 04:09

timgeb