首页 > IT职业 > IT生活 > python ChainMap的突变用法

1、ChainMap支持突变。换句话说,允许更新、添加、删除和弹出键。这种情况这些操作只作用于第一个映射。
>>> from collections import ChainMap
>>> numbers = {"one": 1, "two": 2}
>>> letters = {"a": "A", "b": "B"}
>>> alpha_num = ChainMap(numbers, letters)
>>> alpha_num
ChainMap({'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'})
>>> # Add a new key-value pair
>>> alpha_num["c"] = "C"
>>> alpha_num
ChainMap({'one': 1, 'two': 2, 'c': 'C'}, {'a': 'A', 'b': 'B'})
>>> # Update an existing key
>>> alpha_num["b"] = "b"
>>> alpha_num
ChainMap({'one': 1, 'two': 2, 'c': 'C', 'b': 'b'}, {'a': 'A', 'b': 'B'})
>>> # Pop keys
>>> alpha_num.pop("two")
2
>>> alpha_num.pop("a")
Traceback (most recent call last):
...
KeyError: "Key not found in the first mapping: 'a'"
>>> # Delete keys
>>> del alpha_num["c"]
>>> alpha_num
ChainMap({'one': 1, 'b': 'b'}, {'a': 'A', 'b': 'B'})
>>> del alpha_num["a"]
Traceback (most recent call last):
...
KeyError: "Key not found in the first mapping: 'a'"
>>> # Clear the dictionary
>>> alpha_num.clear()
>>> alpha_num
ChainMap({}, {'a': 'A', 'b': 'B'})
2、改变给定链映射内容的操作只会影响第一个映射,即使试图改变列表中的其他映射中的键。
可以使用此行为创建可更新的链映射,而不修改原始输入字典。在这种情况下,您可以使用空字典作为ChainMap的第一个参数。
>>> from collections import ChainMap
>>> numbers = {"one": 1, "two": 2}
>>> letters = {"a": "A", "b": "B"}
>>> alpha_num = ChainMap({}, numbers, letters)
>>> alpha_num
ChainMap({}, {'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'})
>>> alpha_num["comma"] = ","
>>> alpha_num["period"] = "."
>>> alpha_num
ChainMap(
{'comma': ',', 'period': '.'},
{'one': 1, 'two': 2},
{'a': 'A', 'b': 'B'}
)
以上就是python ChainMap的突变用法,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/75/viewspace-2828350/ ,如需转载,请注明出处,否则将追究法律责任。