Python update()方法使用键和值对更新字典。如果不存在,则会插入键/值。如果字典中已经存在键/值,它将更新键/值。
它还允许键/值对的迭代,以更新字典。例如:update(a = 10,b = 20)等。
dict.update - 语法
update([other])
dict.update - 参数
other:这是键/值对的列表。
dict.update - 返回
它返回None。
这是一个简单的示例,它通过传递键/值对来更新字典。此方法更新字典。请参见下面的示例。
# Python dictionary update() Method # Creating a dictionary einventory = {Fan: 200, Bulb:150, Led:1000} print("Inventory:",einventory) # Calling Method einventory.update({cooler:50}) print("Updated inventory:",einventory)
输出:
Inventory: {Fan: 200, Bulb: 150, Led: 1000}
Updated inventory: {Fan: 200, Bulb: 150, Led: 1000, cooler: 50}如果字典中已经存在元素(键/值)对,它将覆盖它。请参见下面的示例。
# Python dictionary update() Method # Creating a dictionary einventory = {Fan: 200, Bulb:150, Led:1000,cooler:50} print("Inventory:",einventory) # Calling Method einventory.update({cooler:50}) print("Updated inventory:",einventory) einventory.update({cooler:150}) print("Updated inventory:",einventory)
输出:
Inventory: {Fan: 200, Bulb: 150, Led: 1000, cooler: 50}
Updated inventory: {Fan: 200, Bulb: 150, Led: 1000, cooler: 50}
Updated inventory: {Fan: 200, Bulb: 150, Led: 1000, cooler: 150}update()方法还允许将可迭代的键/值对用作参数。请参阅,下面的示例将两个值传递给字典并对其进行更新。
# Python dictionary update() Method # Creating a dictionary einventory = {Fan: 200, Bulb:150, Led:1000} print("Inventory:",einventory) # Calling Method einventory.update(cooler=50,switches=1000) print("Updated inventory:",einventory)
输出:
Inventory: {Fan: 200, Bulb: 150, Led: 1000}
Updated inventory: {Fan: 200, Bulb: 150, Led: 1000, cooler: 50, switches: 1000}