1

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?

Baz
  • 12,713
  • 38
  • 145
  • 268
  • Does this answer your question? [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) – mkrieger1 Jan 18 '20 at 21:42
  • 2
    just do: `{l.upper():c for l, c in counter.items()}` it will leave you with two keys. – YOLO Jan 18 '20 at 21:44
  • Oh you want to sum the values as well. Then you need to use some `if`s and `+`s, too. – mkrieger1 Jan 18 '20 at 21:44
  • @YOLO That doesn't combine the two existing values for `A` and `a`, though. – chepner Jan 18 '20 at 21:44

2 Answers2

3

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
chepner
  • 497,756
  • 71
  • 530
  • 681
1

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}
wjandrea
  • 28,235
  • 9
  • 60
  • 81