I have a dictionary that looks like this:
d = {'A':110, 'a':100, 'T':50, 't':5}
I want to change the keys to upper case and combine A+a
and T+t
and add their values, so that the resulting dictionary looks like this:
d = {'A': 210, T: 55}
This is what I tried:
for k, v in d.items():
k.upper(), v
and the result is:
('A', 110)
('A', 100)
('T', 50)
('t', 5)
I looks like tuples but I want to change it in the dictionary, so I tried to write a function:
def Upper(d):
for k, v in d.items:
k.upper(), v
return d
but it returns the dictionary unchanged.
After I have changed the keys to upper case I had found this solution to how to add values of keys in a dictionary:
dict([(x, a[x] + b[x]) if (x in a and x in b) else (x, a[x]) if (x in a) else (x, b[x])
but first I need to get the keys to upper case!
Counter
does this quite nicely
>>> d = {'A':110, 'a':100, 'T':50, 't':5}
>>> from collections import Counter
>>> c = Counter()
>>> for k,v in d.items():
... c.update({k.upper(): v})
...
>>> c
Counter({'A': 210, 'T': 55})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With