
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
In [1]: x = {'a': 1, 'b': 2} ...: y = {'b': 3, 'c': 4} ...: In [2]: {**x,**y} Out[2]: {'a': 1, 'b': 3, 'c': 4} In [3]: from collections import Counter In [4]: dict(Counter(x)+Counter(y)) Out[4]: {'a': 1, 'b': 5, 'c': 4} In [5]: Counter(x) Out[5]: Counter({'a': 1, 'b': 2}) In [6]: |
另外一种笨方法
1 2 3 4 5 6 7 8 9 10 11 |
>>> x = { 'apple': 1, 'banana': 2 } >>> y = { 'banana': 10, 'pear': 11 } >>> for k, v in y.items(): ... if k in x.keys(): ... x[k] += v ... else: ... x[k] = v ... >>> x {'pear': 11, 'apple': 1, 'banana': 12} |
第三种办法
1 2 3 4 5 6 7 8 9 10 11 |
def union_dict(*objs): _keys = set(sum([obj.keys() for obj in objs],[])) _total = {} for _key in _keys: _total[_key] = sum([obj.get(_key,0) for obj in objs]) return _total obj1 = {'a':1,'b':2} obj2 = {'a':1,'b':2} print union_dict(obj1,obj2) |

