首页 > 文章列表 > python update合并字典的方法

python update合并字典的方法

Python update
139 2022-08-07

1、每次调用update()现有键的值,键都会更新为新值。

在这种情况下,您将无法使用不同的范围来优先访问重复密钥。

2、使用update(),为给定键提供的最后一个值将永远占上风。在循环中创建常规字典需要O(nm),而从最终字典中检索一个键需要O(1)。

实例

>>> for_adoption = {"dogs": 10, "cats": 7, "pythons": 3}
>>> vet_treatment = {"cats": 2, "dogs": 1}
 
>>> # Merge dictionaries with .update()
>>> pets = {}
>>> pets.update(for_adoption)
>>> pets.update(vet_treatment)
>>> pets
{'dogs': 1, 'cats': 2, 'pythons': 3}

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。