【问题标题】:How to append the sum of keys of each dictionary to another key?如何将每个字典的键总和附加到另一个键?
【发布时间】:2021-12-13 22:52:20
【问题描述】:

我的 json 格式如下:-

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}]}]}

现在我想创建一个新的字典列表。如下:-

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}]

我能够将值除以所需的格式,但我无法将每个字典的总分键“len”附加到每个字典结果的 total 中。它正在计算所有字典的全部值。我得到的代码和输出如下:-

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)

我得到的输出:-

[{'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}]   

如您所见,它汇总了所有值并将它们附加到键 total。如何将每个字典 score 的总和附加到每个字典 resulttotal 键,如下所示?

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}]

【问题讨论】:

  • @DaniMesejo sum of len(89+27 =116)

标签: python json list dictionary sum


【解决方案1】:

使用sum 获取总数:

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

输出

[{'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}]

或等效的 for 循环:

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

【讨论】:

    猜你喜欢
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2014-04-22
    相关资源
    最近更新 更多