Home > Net >  Get the sum of json objects categorically in python
Get the sum of json objects categorically in python

Time:05-31

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

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.

CodePudding user response:

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}
  • Related