如何在嵌套字典中对列表的元素求和

How can i sum the elements of the list in the nested dictionary

提问人:SH Chung 提问时间:7/21/2023 最后编辑:Andrej KeselySH Chung 更新时间:7/22/2023 访问量:25

问:

我有一本字典,如下所示

dict= {
('201', '1'): {'357': [1, 67500], '360': [1, 40000], '362': [2, 45000], '365': [1, 12500]},
('301', '2'): {'322': [5, 237500]},
('301', '1'): {'325': [10, 675000]}
}

我想得到如下结果:

'''165000 is the sum of the second elements of the lists e.g. [1, 67500]'''

{
('201', '1'): 165000},
('301', '2'): 237500},
('301', '1'): 675000}
}

你能展示你的代码吗--- 任何解决方案都会有所帮助 - 理解、计数器等

{('201', '1'): 165000},('301', '2'): 237500},('301', '1'): 675000}}
python loops 字典 嵌套 列表理解

评论


答:

0赞 Andrej Kesely 7/22/2023 #1

尝试:

dct = {
    ("201", "1"): {
        "357": [1, 67500],
        "360": [1, 40000],
        "362": [2, 45000],
        "365": [1, 12500],
    },
    ("301", "2"): {"322": [5, 237500]},
    ("301", "1"): {"325": [10, 675000]},
}

out = {}
for k, v in dct.items():
    out[k] = sum(vv for _, vv in v.values())

print(out)

指纹:

{("201", "1"): 165000, ("301", "2"): 237500, ("301", "1"): 675000}

艺术

out = {k: sum(vv for _, vv in v.values()) for k, v in dct.items()}

评论

1赞 SH Chung 7/24/2023
真的很感谢~~ ^^