字典合并问题
利用 update 方法,合并后是修改原来的字典,而不是新建一个字典作为返回值,比如:
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
解决方法一
z = dict(x.items() + y.items())
其中相同的键的值会被后一个字典的值覆盖
另外,如果是 Python3:
>>> z = dict(list(x.items()) + list(y.items()))
解决方法二
手动复制一遍再 update
z = x.copy()
z.update(y)
Last updated
Was this helpful?