如何无需指定列表名,对字典内嵌套列表的数值求和?
Solution: Generic Sum Calculation for Dictionary Values
Got it, let's fix this without having to hardcode each key name—this is straightforward with a Python dictionary comprehension, which lets us process every key-value pair dynamically.
Complete Working Code
Here's the code that does exactly what you need, no manual key specification required:
original_dict = {'swimming': ['1000', '1200'], 'fencing': ['200', '100'], 'athletics': ['600']} result_dict = { key: [str(sum(int(num_str) for num_str in value_list))] for key, value_list in original_dict.items() } print(result_dict)
How This Works (Breakdown)
Let's walk through each part so you understand the magic:
original_dict.items()loops through every key and its corresponding list in the dictionary—no need to name each sport explicitly!- For each list of string numbers, we use
int(num_str)to convert each string to an integer, then pass those integers tosum()to get the total. - We convert the sum back to a string (to match your desired output format) and wrap it in a list
[str(...)]to keep the nested structure you want. - The dictionary comprehension builds the new dictionary with the original keys and the processed summed values.
Expected Output
Running this code will give you the exact structure you're targeting:
{'swimming': ['2200'], 'fencing': ['300'], 'athletics': ['600']}
This approach is also scalable—if you add more sports to your original dictionary later, the code will handle them automatically without any changes.
内容的提问来源于stack exchange,提问作者Fletcher Adams
相关产品推荐
相关产品推荐

