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})
upper()
method doesn't change anything. You can use the following code:
def capitalize_keys(d):
result = {}
for key, value in d.items():
upper_key = key.upper()
result[upper_key] = result.get(upper_key, 0) + value
return result
defaultdict
is helpful:
>>> from collections import defaultdict
>>> d = {'A':110, 'a':100, 'T':50, 't':5}
>>> new_d = defaultdict(int)
>>> for key, val in d.iteritems():
... new_d[key.upper()] += val
...
>>> dict(new_d)
{'A': 210, 'T': 55}
With this function (corrected):
>>> def upper_kdict(d):
... r = {}
... for k, v in d.items():
... K = k.upper()
... r[K] = v if not r.__contains__(K) else v + r[K]
... return r
...
>>>
>>> d = {'a': 100, 'A': 110, 'b': 20, 'B': 1000, 'C': 150, 'c': 100, 'd': 180}
>>> upper_kdict(d)
{'A': 210, 'C': 250, 'B': 1020, 'D': 180}
d = {'A':110, 'a':100, 'T':50, 't':5}
{i.lower(): d.get(i.lower(),0)+d.get(i.upper(),0) for i in d.keys()}
// {'a': 210, 't': 55}
If you want the keys in upper case then use
{i.upper(): d.get(i.lower(),0)+d.get(i.upper(),0) for i in d.keys()}
// {'A': 210, 'T': 55}
Output:
I think you have to rebuild your dictionary. Example:
from collections import defaultdict
d={'A':110, 'a':100, 'T':50, 't':5}
def upper(d):
nd=defaultdict(int)
for k, v in d.iteritems():
nd[k.upper()]+=v
return dict(nd)
print d
print upper(d)
Output:
{'A': 110, 'a': 100, 'T': 50, 't': 5}
{'A': 210, 'T': 55}
Or use the solution from @citxx with result.get(upper_key, 0) + value
and avoid the defaultdict altogether.
Use a very long dictionary comprehension:
d = {'A':110, 'a':100, 'T':50, 't':5}
d = dict((k, v + d.get(k.lower(), 0)) if (k == k.upper())
else (k.upper(), v) for (k, v) in d.items()
if ((k == k.upper()) or (k == k.lower() and not (k.upper() in d))))
print d
Output:
{'A': 210, 'T': 55}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.