Python/Python3中如何对值为列表的字典元素求和及指定键的列表值求和
Hey there! Let's break down solutions to your two Python dictionary summation questions clearly:
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
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

