Python 字典 update() 方法



Python 字典 update() 方法用於更新字典的鍵值對。這些鍵值對是從另一個字典或可迭代物件(如包含鍵值對的元組)更新的。

如果鍵值對已存在於字典中,則使用 update() 方法將現有鍵更改為新值。另一方面,如果鍵值對不存在於字典中,則此方法會插入它。

語法

以下是 Python 字典 update() 方法的語法:

dict.update(other)

引數

  • other - 要新增到 dict 的字典。

返回值

此方法不返回值。

示例

以下示例顯示了 Python 字典 update() 方法的使用。這裡建立了一個字典 'dict',它包含針對鍵 'Name' 和 'Age' 的值:'Zara' 和 '7'。然後建立另一個字典 'dict2',它包含鍵 'Sex' 及其對應值 'female'。此後,使用 update() 方法,'dict' 將使用 'dict2' 中提供的項進行更新。

# Creating the first dictionary
dict = {'Name': 'Zara', 'Age': 7}
# Aanother dictionary
dict2 = {'Sex': 'female' }
# using the update() method
dict.update(dict2)
print ("Value : %s" %  dict)

當我們執行以上程式時,它會產生以下結果:

Value : {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}

示例

在下面的程式碼中,元組列表作為引數傳遞給 update() 方法。這裡,元組的第一個元素充當鍵,第二個元素充當值。

# creating a dictionary
dict_1 = {'Animal': 'Lion'}
# updating the dictionary
res = dict_1.update([('Kingdom', 'Animalia'), ('Order', 'Carnivora')])
print('The updated dictionary is: ',dict_1)

執行上述程式碼時,我們得到以下輸出:

The updated dictionary is:  {'Animal': 'Lion', 'Kingdom': 'Animalia', 'Order': 'Carnivora'}

示例

在這裡,使用 update() 方法更新了現有的鍵 'RollNo'。此鍵已存在於字典中。因此,它將使用新的鍵值對進行更新。

dict_1 = {'Name': 'Rahul', 'Hobby':'Singing', 'RollNo':34}
# updating the existing key
res = dict_1.update({'RollNo':45})
print('The updated dictionary is: ',dict_1)

以下是上述程式碼的輸出:

The updated dictionary is:  {'Name': 'Rahul', 'Hobby': 'Singing', 'RollNo': 45}

示例

在下面給出的示例中,鍵:值對指定為關鍵字引數。當呼叫方法時,引數的關鍵字(名稱)用於為其賦值。

# creating a dictionary
dict_1 = {'Animal': 'Lion'}
res = dict_1.update(Order = 'Carnivora', Kingdom = 'Animalia')
print(dict_1)

上述程式碼的輸出如下:

{'Animal': 'Lion', 'Order': 'Carnivora', 'Kingdom': 'Animalia'}
python_dictionary.htm
廣告