python dict(字典)中的update函数

定义

dict1 = {
    
    }
dict2 = {
    
    }
dict1.update(dict2)

update() 函数把字典dict2的 键 / 值 对更新到dict1里。

例子

dict1 = {
    
    'Name': 'Jack', 'Age': 10}
dict2 = {
    
    'Sex': 'boy' }

dict1.update(dict2)
print("Value : %s" %  dict1)
#Value : {'Name': 'Jack', 'Age': 10, 'Sex': 'boy'}

注意

用 update 更新字典 dict1,会有两种情况:

  1. 有相同的键时:会使用最新的字典 dict2 中 该 key 对应的 value 值。
  2. 有新的键时:会直接把字典 dict2 中的 key、value 加入到 dict1 中。
dict1 = {
    
    1: 2, 2: 2}
dict2 = {
    
    1: 1, 3: 3}
dict1.update(dict2)
print(dict1)
#{1: 1, 2: 2, 3: 3}

猜你喜欢

转载自blog.csdn.net/qq_52855744/article/details/125505303