可以通过update()方法将一个字典的内容添加到另一个字典中,如下:
>>> d={'a':1,'b':2,'c':3}
>>> dd={'c':11,'d':22,'e':33}
>>> d.update(dd) #将字典dd 添加到字典d中
>>> d #字典d发生变化
{'b': 2, 'a': 1, 'd': 22, 'e': 33, 'c': 11}
>>> dd #字典dd保持不变
{'d': 22, 'e': 33, 'c': 11}
其实,update()方法与下面的for循环功能一致:
>>> d={'a':1,'b':2,'c':3}
>>> dd={'c':11,'d':22,'e':33}
>>> dd.items()
dict_items( [('d', 22), ('e', 33), ('c', 11)] )
>>> for (key,value) in dd.items():
d[key]=value
>>> d #字典d发生变化
{'b': 2, 'a': 1, 'd': 22, 'e': 33, 'c': 11}
>>> dd #字典dd保持不变
{'d': 22, 'e': 33, 'c': 11}