Reputation: 13125
I wish to convert the keys in a dictionary to capitals, but I want the values summed of, for example, "A" and "a":
counter = {"A":1,"a":2,b:3}
this doesn't quite do it:
counter = {l.upper():c for l in counter}
What should I be doing?
Upvotes: 1
Views: 59
Reputation: 32944
Use a defaultdict
with int
, then iterate over your dict, convert the keys, and add the values.
from collections import defaultdict
counter = {"A": 1, "a": 2, 'b': 3}
d = defaultdict(int)
for k, v in counter.items():
k = k.upper()
d[k] += v
print(dict(d)) # -> {'A': 3, 'B': 3}
Upvotes: 1
Reputation: 530970
Use a defaultdict
.
from collections import defaultdict
d = defaultdict(int)
for k, v in counter.items():
d[k.upper()] += v
d = dict(d) # optional, if you really want just a regular dict in the end
Upvotes: 3