python dict update函数
Python 字典(Dictionary) update() 函数把字典dict2的键/值对更新到dict里。
dict.update(dict2)
- dict2 -- 添加到指定字典dict里的字典。
- 该方法没有任何返回值。
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print("Value : %s" % dict)
#Value : {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}
用 update 更新字典 a,会有两种情况:
- (1)有相同的键时:会使用最新的字典 b 中 该 key 对应的 value 值。
- (2)有新的键时:会直接把字典 b 中的 key、value 加入到 a 中。
a = {1: 2, 2: 2}
b = {1: 1, 3: 3}
a.update(b)
print(a)
#{1: 1, 2: 2, 3: 3}
浙公网安备 33010602011771号