How to use the update function in Python

In Python, the update() function is used to update key-value pairs from one dictionary to another.

Here is the syntax for the update() function:

dict.update([other])

In this case, “other” can be a dictionary or an iterable object that contains key-value pairs (such as a list of tuples).

When other is a dictionary, the update() function will add any key-value pairs from other to the original dictionary. If the key already exists in the original dictionary, the corresponding value will be updated; if the key does not exist in the original dictionary, a new key-value pair will be added.

When other is an iterable object, the update() function will add key-value pairs from the iterable object to the original dictionary, where the format of the key-value pairs should be (key, value).

Here are some examples of how to use the update() function:

# 示例1:将一个字典中的键值对更新到另一个字典中
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)  # 输出:{'a': 1, 'b': 3, 'c': 4}

# 示例2:将一个可迭代对象中的键值对添加到字典中
dict1 = {'a': 1, 'b': 2}
tuple_list = [('b', 3), ('c', 4)]
dict1.update(tuple_list)
print(dict1)  # 输出:{'a': 1, 'b': 3, 'c': 4}

It’s important to note that the update() function will modify the original dictionary directly and will not return a new dictionary. If you need to create a new dictionary, you can use the dictionary’s copy method, such as dict.copy() or the dict() function.

bannerAds