Python 3 – 字典 update()方法
Python是一種腳本語言,也是一種高級編程語言。愛掏網(wǎng) - it200.com在Python中,字典是一種非常常見的數(shù)據(jù)類型,字典是一種鍵-值對的集合,鍵和值是一一對應(yīng)的關(guān)系。愛掏網(wǎng) - it200.com在Python中,可以使用字典的update()方法來更新字典中的值。愛掏網(wǎng) - it200.com
update()方法是Python中字典的一個(gè)內(nèi)置方法,它用于將一個(gè)字典中的鍵值對更新或添加到另一個(gè)字典中。愛掏網(wǎng) - it200.comupdate()方法接受另一個(gè)字典作為參數(shù),將另一個(gè)字典中的鍵值對添加到當(dāng)前字典中,如果有相同的鍵,則以另一個(gè)字典中的值為準(zhǔn)。愛掏網(wǎng) - it200.comupdate()方法的用法如下:
dict.update([other])
其中,參數(shù)other表示要添加的字典。愛掏網(wǎng) - it200.com
update()方法的用法舉例
下面是一個(gè)簡單的示例,展示如何使用update()方法:
dict1 = {'name': 'xiaoming', 'age': 18}
dict2 = {'sex': 'male'}
# 添加新的鍵值對,如果有相同的鍵,則以dict2中的值為準(zhǔn)
dict1.update(dict2)
print(dict1)
輸出結(jié)果為:
{'name': 'xiaoming', 'age': 18, 'sex': 'male'}
在這個(gè)例子中,我們首先定義了一個(gè)名為dict1的字典,然后創(chuàng)建了一個(gè)名為dict2的字典,其中只有一個(gè)鍵值對- ‘sex’ : ‘male’。愛掏網(wǎng) - it200.com然后,我們調(diào)用了update()方法并傳遞了dict2作為參數(shù),這將更新dict1字典中的值,將字典dict2中的鍵值對合并到dict1中同時(shí)更新重復(fù)的鍵。愛掏網(wǎng) - it200.com
update()方法添加多個(gè)字典
在Python中,可以一次添加多個(gè)字典到目標(biāo)字典中。愛掏網(wǎng) - it200.com下面是一個(gè)示例:
dict1 = {'name': 'xiaoming', 'age': 18}
dict2 = {'sex': 'male'}
dict3 = {'country': 'China'}
# 將dict2和dict3兩個(gè)字典合并到dict1字典中
dict1.update(dict2)
dict1.update(dict3)
print(dict1)
輸出結(jié)果為:
{'name': 'xiaoming', 'age': 18, 'sex': 'male', 'country': 'China'}
在這個(gè)例子中,我們首先定義了一個(gè)名為dict1的字典,然后創(chuàng)建了兩個(gè)名為dict2和dict3的字典,每個(gè)字典中都只有一個(gè)鍵值對。愛掏網(wǎng) - it200.com然后我們使用update()方法將字典dict2和dict3添加到字典dict1中,這將合并所有的鍵值對到一個(gè)字典中。愛掏網(wǎng) - it200.com
update()方法可以傳遞多個(gè)參數(shù)
在Python中,update()方法不僅可以接受一個(gè)字典作為參數(shù),還可以接受多個(gè)字典。愛掏網(wǎng) - it200.com下面是一個(gè)示例:
dict1 = {'name': 'xiaoming', 'age': 18}
dict2 = {'sex': 'male'}
dict3 = {'country': 'China'}
# 將dict2和dict3兩個(gè)字典合并到dict1字典中
dict1.update(dict2, dict3)
print(dict1)
輸出結(jié)果為:
{'name': 'xiaoming', 'age': 18, 'sex': 'male', 'country': 'China'}
在這個(gè)例子中,我們使用update()方法將dict2和dict3兩個(gè)字典合并到dict1字典中。愛掏網(wǎng) - it200.com注意,這里我們沒有使用額外的方括號或逗號,只是傳遞了多個(gè)字典作為參數(shù)。愛掏網(wǎng) - it200.com
update()方法可以使用包含鍵值對的元組、列表、集合等
在Python中,update()方法不僅可以接受字典作為參數(shù),還可以接受包含鍵值對的元組、列表、集合等作為參數(shù)。愛掏網(wǎng) - it200.com下面是一個(gè)示例:
dict1 = {'name': 'xiaoming', 'age': 18}
tuple1 = (('sex', 'male'), ('country', 'China'))
list1 = [('phone', '123456'), ('email', 'abc@123.com')]
set1 = {'hobby': 'swimming', 'height': 170}
# 將tuple1、list1和set1分別添加到dict1中
dict1.update(tuple1)
dict1.update(list1)
dict1.update(set1)
print(dict1)
輸出結(jié)果為:
{'name': 'xiaoming', 'age': 18, 'sex': 'male', 'country': 'China', 'phone': '123456', 'email': 'abc@123.com', 'hobby': 'swimming', 'height': 170}
在這個(gè)例子中,我們首先創(chuàng)建了一個(gè)名為dict1的字典,然后創(chuàng)建了一個(gè)元組tuple1、一個(gè)列表list1和一個(gè)集合set1,它們包含了鍵值對。愛掏網(wǎng) - it200.com然后我們使用update()方法將tuple1、list1和set1分別添加到字典dict1中,這將合并所有的鍵值對到一個(gè)字典中。愛掏網(wǎng) - it200.com