Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python list of dictionaries add a value by key

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading