利用collections.MutableMappingupdate()方法更新字典的多种用法
update() 方法是Python中collections模块MutableMapping类提供的方法之一,用于更新字典。它的作用是将指定的键值对添加到字典中,如果键已经存在,则更新对应的值。
update() 方法可以接受各种可迭代对象作为参数,包括字典、列表、元组等。如果参数是字典,则将字典中所有的键值对添加到当前字典中。如果参数是可迭代对象且每个元素是一个键值对的列表、元组或字典,则将每个键值对添加到当前字典中。
下面是一些使用update()方法的例子:
例1:传入一个字典作为参数
fruits = {"apple": 2, "banana": 3}
inventory = {"orange": 4, "grape": 5}
inventory.update(fruits)
print(inventory)
# 输出: {'orange': 4, 'grape': 5, 'apple': 2, 'banana': 3}
在这个例子中,fruits是一个字典,inventory是另一个字典。通过调用inventory.update(fruits)方法,将fruits字典中的键值对添加到inventory字典中。
例2:传入一个键值对的列表作为参数
fruits = [("apple", 2), ("banana", 3)]
inventory = {"orange": 4, "grape": 5}
inventory.update(fruits)
print(inventory)
# 输出: {'orange': 4, 'grape': 5, 'apple': 2, 'banana': 3}
在这个例子中,fruits是一个包含键值对的列表,inventory是一个字典。通过调用inventory.update(fruits)方法,将fruits列表中的键值对添加到inventory字典中。
例3:传入一个包含键值对的元组作为参数
fruits = (("apple", 2), ("banana", 3))
inventory = {"orange": 4, "grape": 5}
inventory.update(fruits)
print(inventory)
# 输出: {'orange': 4, 'grape': 5, 'apple': 2, 'banana': 3}
在这个例子中,fruits是一个包含键值对的元组,inventory是一个字典。通过调用inventory.update(fruits)方法,将fruits元组中的键值对添加到inventory字典中。
例4:传入一个列表中的字典作为参数
fruits = [{"apple": 2}, {"banana": 3}]
inventory = {"orange": 4, "grape": 5}
inventory.update(fruits)
print(inventory)
# 输出: {'orange': 4, 'grape': 5, 'apple': 2, 'banana': 3}
在这个例子中,fruits是一个列表,列表中的元素是字典。inventory是一个字典。通过调用inventory.update(fruits)方法,将列表中的每个字典的键值对添加到inventory字典中。
例5:传入多个字典作为参数
fruits = {"apple": 2}
inventory = {"orange": 4}
inventory.update(fruits, banana=3)
print(inventory)
# 输出: {'orange': 4, 'apple': 2, 'banana': 3}
在这个例子中,除了传入fruits字典之外,还传入了一个banana=3的键值对。通过调用inventory.update(fruits, banana=3)方法,将fruits字典和banana=3键值对添加到inventory字典中。
总结:
update() 方法可以接受不同类型的参数,包括字典、列表、元组等。它在更新字典时非常有用,可以将其他字典、键值对等添加到当前字典中。这使得我们可以方便地将多个键值对合并到一个字典中,或者更新字典中已经存在的键的值。
