data = [
{
'name': 'Jack',
'points': 10
},
{
'name': 'John',
'points': 12
},
{
'name': 'Jack',
'points': 15
},
{
'name': 'Harry',
'points': 11
}
]
Output:
Jack: 25 points ,
John: 12 points ,
Harry: 11 points
Is there anyway to achieve this without using for loop ?
I can achieve this by storing key value pair or name and points and adding the points if already exists in the dictionary. But is there any alternative way to achieve this ?
>Solution :
You can use groupby from itertools:
from itertools import groupby
key = lambda d: d['name']
result = {n: sum(v['points'] for v in vs) for n, vs in groupby(sorted(data, key=key), key)}
Result:
{'Harry': 11, 'Jack': 25, 'John': 12}