How to change the keys in the dictionary to uppercase and add the values ​​of the same key to the resulting dictionary?

I have a dictionary that looks like this:

d = {'A':110, 'a':100, 'T':50, 't':5} 

I want to change the keys to uppercase 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:

 ('A', 110) ('A', 100) ('T', 50) ('t', 5) 

I look 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 changed the keys to uppercase, I found this solution how to add key values ​​to the 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 in uppercase!

+4
source share
6 answers

Counter makes it pretty nice

 >>> 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}) 
+9
source

upper() method does not 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 
+4
source

defaultdict is useful:

 >>> 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} 
+2
source

I think you need to rebuild the 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) 

Conclusion:

 {'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 generally avoid the defaultdict value.

+1
source

Using this function (fixed):

 >>> 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} 
+1
source

Use a very long vocabulary understanding:

 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 

Conclusion:

 {'A': 210, 'T': 55} 
0
source

Source: https://habr.com/ru/post/1401341/


All Articles