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

Get the sum of json objects categorically in python

I am working on a problem where I want to get the sum of JSON objects categorically in a hashmap. Here’s my idea of what the hashmap should look like:

{name: totalScore}

here’s my sample JSON data:

[
    {
        "name": "Hilary Carr",
        "submissions": [
            {
                "name": "Laudantium deleniti beatae fuga.",
                "date": "05/12/2021",
                "score": 37
            }
        ]
    },
{
        "name": "Frederick Williamson",
        "submissions": [
            {
                "name": "Expedita architecto voluptas autem veniam.",
                "date": "03/05/2009",
                "score": 47
            },
            {
                "name": "Animi facere excepturi.",
                "date": "01/02/2021",
                "score": 100
            }
        ]
    }
]

Here’s what I have tried

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

sums = {}
score = 0
for i in json_data:
    for j in i['submissions']:
        score += j['score']
    sums[i['name']] = sums.get(i['name'], 0) + score

and here’s what I get:

{
    "Frederick Williamson": 184,
    "Hilary Carr": 37
}

But it should come out to be:

{
    "Frederick Williamson": 147,
    "Hilary Carr": 37
}

It might be a trivial mistake, but can you please help me with this.

>Solution :

You can use dict-comprehension to sum scores of different persons:

lst = [
    {
        "name": "Hilary Carr",
        "submissions": [
            {
                "name": "Laudantium deleniti beatae fuga.",
                "date": "05/12/2021",
                "score": 37,
            }
        ],
    },
    {
        "name": "Frederick Williamson",
        "submissions": [
            {
                "name": "Expedita architecto voluptas autem veniam.",
                "date": "03/05/2009",
                "score": 47,
            },
            {
                "name": "Animi facere excepturi.",
                "date": "01/02/2021",
                "score": 100,
            },
        ],
    },
]

out = {d["name"]: sum(s["score"] for s in d["submissions"]) for d in lst}

print(out)

Prints:

{'Hilary Carr': 37, 'Frederick Williamson': 147}
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