Python如何使用Collections.UserDict(代码示例)

用于存储数据值(如Map)的无序数据值集合称为Python字典。与仅包含单个值作为元素的其他数据类型不同, 字典具有核心价值对。字典中提供了键值以使其更优化。
注意:有关更多信息, 请参阅Python字典
Collections.UserDictPython支持字典就像一个叫做UserDict存在于collections模块。此类充当字典对象周围的包装器类。当一个人想要创建自己的具有某些修改功能或某些新功能的字典时, 此类非常有用。它可以被视为为字典添加新行为的一种方式。此类将字典实例作为参数, 并模拟保存在常规字典中的字典。该类的data属性可访问该词典。
语法如下:

collections.UserDict([initialdata])

范例1:
# Python program to demonstrate # userdictfrom collections import UserDictd = { '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 # userdictfrom 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, in d.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

【Python如何使用Collections.UserDict(代码示例)】首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

    推荐阅读