两个字典a = {'a': 1, 'b': 2, 'c': 3}, b = {'b': 4, 'c': 6, 'd': 8} 要合并这两个字典,键值同则相加。
两个字典如果不考虑键相同则相加的话,可以使用d1.update(d2)可以很方便合并,但这样的后面的字典到中的值会覆盖字典d1中的值。
>>> a = {'a': 1, 'b': 2}
>>> b = {'a': 8, 'c': 3}
>>> a.update(b)
>>> a
{'a': 8, 'b': 2, 'c': 3}
如果要考虑两个字典,如果考虑键同则值相加的问题,可以使用下面的几种方法:
方法一:
>>> a = {'a': 1, 'b': 2, 'c': 3}
>>> b = {'b': 4, 'c': 6, 'd': 8}
>>> for key,value in b.items():
... if key in a:
... a[key] = value
... else:
... a[key] = value
>>> dict(sorted(a.items(), key=lambda d:d[1]))
{'a': 1, 'b': 6, 'd': 8, 'c': 9}
方法二:
>>> a = {'a': 1, 'b': 2, 'c': 3}
>>> b = {'b': 4, 'c': 6, 'd': 8}
>>> c = {}
>>> for key in list(set(a) | set(b)):
... if a.get(key) and b.get(key):
... c.update({key: a.get(key) b.get(key)})
... else:
... c.update({key: a.get(key) or b.get(key)})
>>> c
{'c': 9, 'd': 8, 'a': 1, 'b': 6}
方法三:
>>> a = {'a': 1, 'b': 2, 'c': 3}
>>> b = {'b': 4, 'c': 6, 'd': 8}
>>> def dict_union(d1, d2):
... keys = d1.keys() | d2.keys()
... temp = {}
... for key in keys:
... temp[key] = sum([d.get(key,0) for d in (d1, d2)])
... return temp
>>> c = dict_union(a, b)
>>> c
{'d': 8, 'a': 1, 'b': 6, 'c': 9}
方法四:
>>> a = {'a': 1, 'b': 2, 'c': 3}
>>> b = {'b': 4, 'c': 6, 'd': 8}
>>> c = {}
>>> for key1 in a:
... for key2 in b:
... if key1 in b:
... c[key1] = a[key1] b[key1]
... else:
... c[key1] = a[key1]
... if key2 not in a:
... c[key2] = b[key2]
>>> c
{'a': 1, 'd': 8, 'b': 6, 'c': 9}
方法五:
>>> a = {'a': 1, 'b': 2, 'c': 3}
>>> b = {'b': 4, 'c': 6, 'd': 8}
>>> c = {}
>>> for key in a:
... if b.get(key):
... c[key] = a[key] b[key]
... else:
... c[key] = a[key]
>>> for key in b:
... if not a.get(key):
... c[key] = b[key]
>>> c
{'a': 1, 'b': 6, 'c': 9, 'd': 8}