詳解Python中defaultdict的具體使用
Python 中的 defaultdict 與 dict
defaultdict 是一個類似字典的容器,屬于 collections 模塊。 它是字典的子類; 因此它具有詞典的所有功能。 然而,defaultdict 的唯一目的是處理 KeyError。
# return true if the defaultdict is a subclass of dict (dictionary) from collections import defaultdict print(issubclass(defaultdict,dict))
輸出:
True
假設(shè)用戶在字典中搜索條目,并且搜索到的條目不存在。 普通字典會出現(xiàn)KeyError,表示該條目不存在。 為了解決這個問題,Python 開發(fā)人員提出了 defaultdict 的概念。
代碼示例:
# normal dictionary ord_dict = { "x" :3, "y": 4 } ord_dict["z"] # --> KeyError
輸出:
KeyError: 'z'
普通字典無法處理未知鍵,當(dāng)我們搜索未知鍵時,它會拋出 KeyError,如上面的代碼所示。
另一方面,defaultdict 模塊的工作方式與 Python 詞典類似。 盡管如此,它仍然具有先進、有用且用戶友好的功能,并且當(dāng)用戶在字典中搜索未定義的鍵時不會拋出錯誤。
相反,它在字典中創(chuàng)建一個條目,并針對該鍵返回一個默認(rèn)值。 為了理解這個概念,讓我們看看下面的實際部分。
代碼示例:
from collections import defaultdict # the default value for the undefined key def def_val(): return "The searched Key Not Present" dic = defaultdict(def_val) dic["x"] = 3 dic["y"] = 4 # search 'z' in the dictionary 'dic' print(dic["z"]) # instead of a KeyError, it has returned the default value print(dic.items())
輸出:
The searched Key Not Present
dict_items([('x', 3), ('y', 4), ('z', 'The searched Key Not Present')])
defaultdict 創(chuàng)建我們嘗試使用該鍵訪問的任何項目,該鍵在字典中未定義。
并且創(chuàng)建這樣一個默認(rèn)項,它調(diào)用我們傳遞給defaultdict的構(gòu)造函數(shù)的函數(shù)對象,更準(zhǔn)確地說,該對象應(yīng)該是一個包含類型對象和函數(shù)的可調(diào)用對象。
在上面的示例中,默認(rèn)項是使用 def_val 函數(shù)創(chuàng)建的,該函數(shù)根據(jù)字典中未定義的鍵返回字符串“搜索到的鍵不存在”。
Python 中的 defaultdict
default_factory 是 __missing__() 方法使用的 defaultdict 構(gòu)造函數(shù)的第一個參數(shù),如果構(gòu)造函數(shù)的參數(shù)丟失,default_factory 將被初始化為 None,這將出現(xiàn) KeyError。
如果 default_factory 是用 None 以外的東西初始化的,它將被分配為搜索到的鍵的值,如上面的示例所示。
Python 中 defaultdict 的有用函數(shù)
字典和defaultdict有很多功能。 我們知道,defaultdict可以訪問字典的所有功能; 然而,這些是 defaultdict 特有的一些最有用的函數(shù)。
Python 中的 defaultdict.clear()
代碼示例:
from collections import defaultdict # the default value for the undefined key def def_val(): return "Not Present" dic = defaultdict(def_val) dic["x"] = 3 dic["y"] = 4 print(f'Before clearing the dic, values of x = {dic["x"]} and y = {dic["y"]}') dic.clear() #dic.clear() -> None. it will remove all items from dic. print(f'After clearing the dic, values of x = {dic["x"]} and y = {dic["y"]}')
輸出:
Before clearing the dic, values of x = 3 and y = 4
After clearing the dic, values of x = Not Present and y = Not Present
正如我們在上面的示例中看到的,字典 dic 中有兩對數(shù)據(jù),其中 x=3 和 y=4。 然而,使用 clear() 函數(shù)后,數(shù)據(jù)已被刪除,x和y的值不再存在,這就是為什么我們得到的x和y不存在。
Python 中的 defaultdict.copy()
代碼示例:
from collections import defaultdict # the default value for the undefined key def def_val(): return "Not Present" dic = defaultdict(def_val) dic["x"] = 3 dic["y"] = 4 dic_copy = dic.copy() # dic.copy will give you a shallow copy of dic. print(f"dic = {dic.items()}") print(f"dic_copy = {dic_copy.items()}")
輸出:
dic = dict_items([('x', 3), ('y', 4)])
dic_copy = dict_items([('x', 3), ('y', 4)])
defaultdict.copy() 函數(shù)用于將字典的淺表副本復(fù)制到另一個我們可以相應(yīng)使用的變量中。
Python 中的 defaultdict.default_factory()
代碼示例:
from collections import defaultdict # the default value for the undefined key def def_val(): return "Not present" dic = defaultdict(def_val) dic["x"] = 3 dic["y"] = 4 print(f"The value of z = {dic['Z']}") print(dic.default_factory()) # default_factory returns the default value for defaultdict.
輸出:
The value of z = Not present
Not present
default_factory()函數(shù)用于為定義的類的屬性提供默認(rèn)值,一般情況下,default_factory的值是函數(shù)返回的值。
Python 中的 defaultdict.get(key, default value)
代碼示例:
from collections import defaultdict # the default value for the undefined key def def_val(): return "Not present" dic = defaultdict(def_val) dic["x"] = 3 dic["y"] = 4 # search the value of Z in the dictionary dic; if it exists, return the value; otherwise, display the message print(dic.get("Z","Value doesn't exist")) # default value is None
輸出:
Value doesn't exist
defaultdict.get() 函數(shù)有兩個參數(shù),第一個是鍵,第二個是鍵的默認(rèn)值,以防該值不存在。
但第二個參數(shù)是可選的。 所以我們可以指定任何消息或值; 否則,它將顯示 None 作為默認(rèn)值。
以上就是詳解Python中defaultdict的具體使用的詳細(xì)內(nèi)容,更多關(guān)于python defaultdict的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python爬蟲豆瓣網(wǎng)的模擬登錄實現(xiàn)
這篇文章主要介紹了python爬蟲豆瓣網(wǎng)的模擬登錄實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08Python自動調(diào)用IE打開某個網(wǎng)站的方法
這篇文章主要介紹了Python自動調(diào)用IE打開某個網(wǎng)站的方法,涉及Python調(diào)用系統(tǒng)win32組件的相關(guān)技巧,需要的朋友可以參考下2015-06-06Python?os.environ實戰(zhàn)應(yīng)用及技巧總結(jié)
這篇文章主要介紹了Python?os.environ實戰(zhàn)應(yīng)用及技巧的相關(guān)資料,os.environ是Python中管理環(huán)境變量的強大工具,提供了對系統(tǒng)環(huán)境變量的訪問和修改能力,需要的朋友可以參考下2025-03-03Python tkinter進度條控件(Progressbar)的使用
這篇文章主要介紹了Python tkinter進度條控件(Progressbar)的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04Django中針對基于類的視圖添加csrf_exempt實例代碼
這篇文章主要介紹了Django中針對基于類的視圖添加csrf_exempt實例代碼,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-02-02