You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python/Python3中如何对值为列表的字典元素求和及指定键的列表值求和

Hey there! Let's break down solutions to your two Python dictionary summation questions clearly:

1. Summing all elements in a dictionary where values are lists

If you need to add up every single number across all the list values in your dictionary, you have a couple of clean approaches:

Approach 1: Concise generator expression (my go-to)

Use a nested generator expression inside the built-in sum() function. It iterates through each list in the dictionary's values, then each number in those lists:

# Example dictionary
sample_dict = {'x': [10, 20, 30], 'y': [40, 50], 'z': [60]}

total_sum = sum(num for lst in sample_dict.values() for num in lst)
print(total_sum)  # Output: 210

Approach 2: Explicit loop (great for beginners)

If you prefer a more step-by-step approach, initialize a total variable and loop through each list, adding its sum to the total:

sample_dict = {'x': [10, 20, 30], 'y': [40, 50], 'z': [60]}

total_sum = 0
for lst in sample_dict.values():
    total_sum += sum(lst)

print(total_sum)  # Output: 210
2. Summing the list values for a specific key (Key1 in your example)

This is straightforward—just access the list via its key and pass it to sum():

dict1 = {'Key1':[99,98,97],'Key2':[89,82,85]}

# Directly sum the list for Key1
key1_total = sum(dict1['Key1'])
print(key1_total)  # Output: 294

Bonus: Safe access (avoid KeyError)

If you're unsure if Key1 might exist in the dictionary, use dict.get() to return an empty list (which sums to 0) if the key is missing:

key1_total = sum(dict1.get('Key1', []))

内容的提问来源于stack exchange,提问作者ProcoderUS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:32:39