Home > database >  How to append the sum of keys of each dictionary to another key?
How to append the sum of keys of each dictionary to another key?

Time:10-29

I have a json format like below:-

l = {'itc': 'ball','classes': [{'scores': [{'len': 89,'width':50},{'len': 27,'width': 17}]},
             {'scores': [{'len': 90,'width': 44},{'len': 0,'width': 0}]},
             {'scores': [{'len': 50,'width': 26},{'len': 0,'width': 0}]}]}

Now I want to create a new list of dictionaries. like below:-

output= [{'result': [{'len': 89, 'width': 50}, {'len': 27, 'width': 17}], 'total': 116}, {'result': [{'len': 90, 'width': 44}, {'len': 0, 'width': 0}], 'total': 90}, {'result': [{'len': 50, 'width': 26}, {'len': 0, 'width': 0}], 'total': 50}]

I was able to divide the values and was able to place in the required format but I am not able to append the total score key 'len' of every dictionary in to the total of every dictionary result. It is calculating the whole values of all the dictionaries. The code and the output I got is as follows:-

added=[]
output=[]
for k,v in l.items():
    if k=='classes':
        for i in v:
            for ke,ve in i.items():
                if ke=='scores':
                    for j in ve:
                        for key,val in j.items():
                            if key=='len':
                                add = val
                                added.append(add)
            sumed=sum(added)
            out={'result':ve,'total':sumed}
            output.append(out)
print(output)

Output I got:-

[{'result': [{'len': 89, 'width': 50}, {'len': 27, 'width': 17}], 'total': 116}, {'result': [{'len': 90, 'width': 44}, {'len': 0, 'width': 0}], 'total': 206}, {'result': [{'len': 50, 'width': 26}, {'len': 0, 'width': 0}], 'total': 256}]   

As you could see that its summing up all the values and appending them to key total. How do I append sum of each dictionary score to the total key of each dictionary result as below?

output= [{'result': [{'len': 89, 'width': 50}, {'len': 27, 'width': 17}], 'total': 116}, {'result': [{'len': 90, 'width': 44}, {'len': 0, 'width': 0}], 'total': 90}, {'result': [{'len': 50, 'width': 26}, {'len': 0, 'width': 0}], 'total': 50}]

CodePudding user response:

Use sum to get the total:

res = [{"result" : cl["scores"], "total" :  sum(d["len"] for d in cl["scores"])} for cl in l["classes"]]
print(res)

Output

[{'result': [{'len': 89, 'width': 50}, {'len': 27, 'width': 17}], 'total': 116}, {'result': [{'len': 90, 'width': 44}, {'len': 0, 'width': 0}], 'total': 90}, {'result': [{'len': 50, 'width': 26}, {'len': 0, 'width': 0}], 'total': 50}]

Or the equivalent, for-loop:

res = []
for cl in l["classes"]:
    scores = cl["scores"]
    total = sum(d["len"] for d in cl["scores"])
    res.append({"result": scores, "total": total})
  • Related