Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change keys in a dictionary to upper case and add values of the same key in the resulting dictionary?

Tags:

python

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!

like image 481
edg Avatar asked Mar 14 '12 10:03

edg


1 Answers

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})
like image 95
John La Rooy Avatar answered Oct 21 '22 23:10

John La Rooy