用于存储数据值(如Map)的无序数据值集合在Python中称为字典。与仅包含单个值作为元素的其他数据类型不同,字典保留key:value
对。字典中提供了键值以使其更优化。
注意:有关更多信息,请参阅Python词典。
Collections.UserDict
Python支持一个字典,例如collections模块中存在一个名为UserDict的容器。此类充当字典对象周围的包装器类。当一个人想要创建自己的具有某些修改函数或某些新函数的字典时,此类非常有用。它可以被视为为字典添加新行为的一种方式。此类将字典实例作为参数,并模拟保存在常规字典中的字典。该类的data属性可访问该词典。
用法:
collections.UserDict([initialdata])
范例1:
# Python program to demonstrate
# userdict
from collections import UserDict
d = {'a':1,
'b':2,
'c':3}
# Creating an UserDict
userD = UserDict(d)
print(userD.data)
# Creating an empty UserDict
userD = UserDict()
print(userD.data)
输出:
{'a':1, 'b':2, 'c':3} {}
范例2:让我们创建一个从UserDict继承的类,以实现自定义词典。
# Python program to demonstrate
# userdict
from collections import UserDict
# Creating a Dictionary where
# deletion is not allowed
class MyDict(UserDict):
# Function to stop deleltion
# from dictionary
def __del__(self):
raise RuntimeError("Deletion not allowed")
# Function to stop pop from
# dictionary
def pop(self, s = None):
raise RuntimeError("Deletion not allowed")
# Function to stop popitem
# from Dictionary
def popitem(self, s = None):
raise RuntimeError("Deletion not allowed")
# Driver's code
d = MyDict({'a':1,
'b':2,
'c':3})
print("Original Dictionary")
print(d)
d.pop(1)
输出:
Original Dictionary {'a':1, 'c':3, 'b':2}
Traceback (most recent call last): File "/home/3ce2f334f5d25a3e24d10d567c705ce6.py", line 35, ind.pop(1) File "/home/3ce2f334f5d25a3e24d10d567c705ce6.py", line 20, in pop raise RuntimeError("Deletion not allowed") RuntimeError:Deletion not allowed Exception ignored in: Traceback (most recent call last): File "/home/3ce2f334f5d25a3e24d10d567c705ce6.py", line 15, in __del__ RuntimeError:Deletion not allowed
相关用法
注:本文由纯净天空筛选整理自nikhilaggarwal3大神的英文原创作品 Collections.UserDict in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。