Python字典推导式问题:实现同键对应整数值累加需求
Hey there! Let's fix this issue where your original dictionary comprehension overwrites values when the same string key pops up multiple times (since dictionary keys have to be unique). That's why you ended up with {"string1": 5, "string2": 2} instead of the desired {"string1": 8, "string2": 2}.
Here are a few clean, practical ways to get the accumulated result:
1. Basic Loop (Intuitive & Easy to Follow)
This is the most straightforward approach—start with an empty dictionary, then iterate through each entry. If the string key already exists, add the integer value to it; if not, set the initial value:
dictionary = {"key":[5, "string1"], "key2":[2, "string2"], "key3":[3, "string1"]} another_dictionary = {} for num, string_key in dictionary.values(): if string_key in another_dictionary: another_dictionary[string_key] += num else: another_dictionary[string_key] = num print(another_dictionary) # Output: {'string1': 8, 'string2': 2}
2. Using collections.defaultdict (Pythonic & Concise)
The defaultdict from the collections module simplifies this work by automatically initializing missing keys with a default value (in this case, 0 for integers). No need to check if the key exists first:
from collections import defaultdict dictionary = {"key":[5, "string1"], "key2":[2, "string2"], "key3":[3, "string1"]} another_dictionary = defaultdict(int) for num, string_key in dictionary.values(): another_dictionary[string_key] += num # Optional: Convert to a regular dictionary if you don't want to keep using defaultdict another_dictionary = dict(another_dictionary) print(another_dictionary) # Output: {'string1': 8, 'string2': 2}
3. Dictionary Comprehension with sum (Compact, Best for Small Datasets)
If you prefer a one-liner style, you can use a comprehension paired with a generator expression to sum values for each unique string key. Note that this iterates over the entire dictionary once per unique key, so it's better suited for smaller datasets:
dictionary = {"key":[5, "string1"], "key2":[2, "string2"], "key3":[3, "string1"]} unique_string_keys = {sk for num, sk in dictionary.values()} another_dictionary = { sk: sum(num for num, key in dictionary.values() if key == sk) for sk in unique_string_keys } print(another_dictionary) # Output: {'string1': 8, 'string2': 2}
Quick Breakdown of Options
- Basic Loop: Perfect for readability, especially if you're new to Python. No external imports required.
defaultdict: The most efficient and clean approach for this use case—highly recommended for most scenarios.- Comprehension with
sum: Compact, but less efficient for large dictionaries due to repeated iterations.
内容的提问来源于stack exchange,提问作者Alexander Lavrenko

