update() 函数把字典dict2的键/值对更新到dict里。如果后面的键有重复的会覆盖前面的
语法
dict.update(dict2)
dict = {'Name': 'Zara','Age': 7}
dict2 = {'Sex': 'female','Name':'zhangsan'}
dict.update(dict2)
print "Value : %s" % dict
结果:
- root@tao:/home/tao# python
- Python 2.7.17 (default,Nov 7 2019,10:07:09)
- [GCC 9.2.1 20191008] on linux2
- Type "help",1)">copyrightcredits" or license" for more information.
- >>> dict = {'Name': Zara',1)">Age7}
- >>> dict2 = {Sexfemale':zhangsan'}
- >>> dict.update(dict2)
- >>> print Value : %s" % dict
- Value : {7,1)">}
- >>>
PHP中类似的语法是array_merge
array_merge() 将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。
如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。
如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。