【Python】冻结字典和集合

2.5 冻结字典和集合

一般情况下,创建好字典和集合之后可以对其中的元素进行添加或删除。但是有时,我们出于某种原因需要将字典和集合进行冻结,不允许对其中的元素进行添加或删除。这个时候,我们就可以使用MappingProxyType函数和frozenset函数直接创建或冻结字典或集合。
创建冻结字典

from icecream import ic
from types import MappingProxyType
dct = MappingProxyType({
    
    'a': 1})
try:
    del dct['a']
except TypeError as err:
ic(err)

ic| err: TypeError(“‘mappingproxy’ object does not support item deletion”)

冻结集合

from icecream import ic
st = {
    
    1, 2}
st.add(3)
ic(st)
st = frozenset(st)
try:
    st.add(4)
except AttributeError as err:
    ic(err)

ic| st: {1, 2, 3}
ic| err: AttributeError(“‘frozenset’ object has no attribute ‘add’”)

可以看到,冻结之后的字典或集合就不能添加元素进去,也不能删除元素了。接下来测试一下,冻结的字典和集合的哈希属性:

from icecream import ic
from types import MappingProxyType
st = frozenset({
    
    1, 2})
dct = MappingProxyType({
    
    'a': 1})
ic(hash(st))
ic(hash(dct))

ic| hash(st): -1826646154956904602
Traceback (most recent call last):
File “E:/BaiduNetdiskWorkspace/FrbPythonFiles/t1.py”, line 7, in
ic(hash(dct))
TypeError: unhashable type: ‘mappingproxy’

我们看到,冻结后的集合变得可哈希了,但是冻结的字典还是不可哈希。

猜你喜欢

转载自blog.csdn.net/crleep/article/details/130481684