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

如何将字典键转为大写并合并大小写同名键的对应值?

How to Convert Dictionary Keys to Uppercase and Sum Values for Case-Insensitive Duplicates

You're absolutely right that a basic dictionary comprehension won't cut it here—because comprehension processes each key-value pair in sequence, and later entries (like "a" in your example) will overwrite the value of the uppercase key ("A") that was processed earlier, leaving you with the last value instead of the sum.

Here are a couple of straightforward ways to get the behavior you want:

Method 1: Basic Loop (No External Libraries)

This is the most explicit approach, great for clarity:

counter = {"A":1,"a":2,"b":3}
uppercase_counter = {}

for key, value in counter.items():
    upper_key = key.upper()
    # Check if the uppercase key already exists, then add or initialize
    if upper_key in uppercase_counter:
        uppercase_counter[upper_key] += value
    else:
        uppercase_counter[upper_key] = value

print(uppercase_counter)  # Output: {'A': 3, 'B': 3}

Method 2: Use collections.defaultdict (Cleaner Syntax)

If you don't mind importing a standard library module, defaultdict simplifies the code by handling default values automatically:

from collections import defaultdict

counter = {"A":1,"a":2,"b":3}
uppercase_counter = defaultdict(int)

for key, value in counter.items():
    # defaultdict(int) sets missing keys to 0 automatically, so we can just add
    uppercase_counter[key.upper()] += value

# Convert back to a regular dictionary if needed
print(dict(uppercase_counter))  # Output: {'A': 3, 'B': 3}

Why Your Original Comprehension Fails

Just to clarify why your initial attempt didn't work:

counter = {l.upper():c for l,c in counter.items()}

When this runs, it processes entries in the order they appear in the original dictionary. First it sets "A":1, then overwrites "A" to 2 when it processes "a":2, and finally sets "B":3. The end result is {'A':2, 'B':3}—not the summed values you're after.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 11:52:49