用於存儲數據值(如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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。