Python dict.update 用法详解及示例
dict.update()
是 Python 中 dict
类型的方法之一,用于更新字典中的键值对。该方法的语法如下:
dict.update([other])
other
:可选参数,用于指定更新字典的其他字典或键值对序列。
下面是3个示例来演示 dict.update()
的使用。
示例1:更新字典中的键值对
# 原始字典
fruit_prices = {'apple': 2, 'banana': 3, 'mango': 5}
print('原始字典:', fruit_prices)
# 更新字典中的键值对
fruit_prices.update({'apple': 4, 'grape': 6})
print('更新后字典:', fruit_prices)
输出:
原始字典: {'apple': 2, 'banana': 3, 'mango': 5}
更新后字典: {'apple': 4, 'banana': 3, 'mango': 5, 'grape': 6}
在示例中,我们首先创建了一个包含水果价格的字典。然后使用 update()
方法,传入一个新的字典来更新原始字典中的键值对。最后打印输出更新后的字典。
示例2:更新字典中的键值对序列
# 原始字典
fruit_prices = {'apple': 2, 'banana': 3, 'mango': 5}
print('原始字典:', fruit_prices)
# 更新字典中的键值对序列
fruit_prices.update([('apple', 4), ('grape', 6), ('orange', 2)])
print('更新后字典:', fruit_prices)
输出:
原始字典: {'apple': 2, 'banana': 3, 'mango': 5}
更新后字典: {'apple': 4, 'banana': 3, 'mango': 5, 'grape': 6, 'orange': 2}
在示例中,我们使用 update()
方法,通过传入一个包含多个键值对的列表来更新字典。最后打印输出更新后的字典。
示例3:合并多个字典
# 原始字典
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = {'e': 5, 'f': 6}
# 合并多个字典
merged_dict = {}
merged_dict.update(dict1)
merged_dict.update(dict2)
merged_dict.update(dict3)
print('合并后的字典:', merged_dict)
输出:
合并后的字典: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
在示例中,我们定义了三个字典 dict1
、dict2
和 dict3
,然后使用空字典作为目标字典,通过多次调用 update()
方法,将这三个字典合并到目标字典中。最后打印输出合并后的字典。