Python - Adding two dictionaries
本问题已经有最佳答案,请猛点这里访问。
如何增加两个字典的值?前任:
1 2 | a = {'a':10,'b':11,'c':20} b = {'a':1,'b':1,'c':1} |
结果必须是
1 | c = {'a':11,'b':12,'c':21} |
通过使用Collections Library的Counter类,您可以轻松添加两个字典,例如:
1 2 3 4 5 6 7 8 9 | from collections import Counter a = {'a':10,'b':11,'c':20} b = {'a':1,'b':1,'c':1} a = Counter(a) b = Counter(b) c = dict(a + b) print c |
产量
1 | {'c': 21, 'b': 12, 'a': 11} |
接下来一些,请表现出一些努力。
1 2 3 4 5 | a = {'a':10,'b':11,'c':20} b = {'a':1,'b':1,'c':1} c = {k: a[k] + b[k] for k in a} print(c) # {'c': 21, 'b': 12, 'a': 11} |
如果我们假设
如果不是这样,您可以尝试以下操作:
1 2 3 4 5 6 7 | a = {'a': 10, 'b': 11, 'c': 20, 'h': 5} b = {'a': 1, 'b': 1, 'c': 1, 'd': 12} all_keys = set(a.keys()) # in Python 3 it can be simplified as `all_keys = set(a)` all_keys.update(b.keys()) # in Python 3 it can be simplified as `all_keys.update(b)` c = {k: a.get(k, 0) + b.get(k, 0) for k in all_keys} print(c) # {'c': 21, 'h': 5, 'a': 11, 'b': 12, 'd': 12} |
注意,我在两个字典上都使用了