詳解Python中defaultdict的具體使用
Python 中的 defaultdict 與 dict
defaultdict 是一個(gè)類似字典的容器,屬于 collections 模塊。 它是字典的子類; 因此它具有詞典的所有功能。 然而,defaultdict 的唯一目的是處理 KeyError。
# return true if the defaultdict is a subclass of dict (dictionary) from collections import defaultdict print(issubclass(defaultdict,dict))
輸出:
True
假設(shè)用戶在字典中搜索條目,并且搜索到的條目不存在。 普通字典會(huì)出現(xiàn)KeyError,表示該條目不存在。 為了解決這個(gè)問題,Python 開發(fā)人員提出了 defaultdict 的概念。
代碼示例:
# normal dictionary ord_dict = { "x" :3, "y": 4 } ord_dict["z"] # --> KeyError
輸出:
KeyError: 'z'
普通字典無法處理未知鍵,當(dāng)我們搜索未知鍵時(shí),它會(huì)拋出 KeyError,如上面的代碼所示。
另一方面,defaultdict 模塊的工作方式與 Python 詞典類似。 盡管如此,它仍然具有先進(jìn)、有用且用戶友好的功能,并且當(dāng)用戶在字典中搜索未定義的鍵時(shí)不會(huì)拋出錯(cuò)誤。
相反,它在字典中創(chuàng)建一個(gè)條目,并針對(duì)該鍵返回一個(gè)默認(rèn)值。 為了理解這個(gè)概念,讓我們看看下面的實(shí)際部分。
代碼示例:
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)建我們嘗試使用該鍵訪問的任何項(xiàng)目,該鍵在字典中未定義。
并且創(chuàng)建這樣一個(gè)默認(rèn)項(xiàng),它調(diào)用我們傳遞給defaultdict的構(gòu)造函數(shù)的函數(shù)對(duì)象,更準(zhǔn)確地說,該對(duì)象應(yīng)該是一個(gè)包含類型對(duì)象和函數(shù)的可調(diào)用對(duì)象。
在上面的示例中,默認(rèn)項(xiàng)是使用 def_val 函數(shù)創(chuàng)建的,該函數(shù)根據(jù)字典中未定義的鍵返回字符串“搜索到的鍵不存在”。
Python 中的 defaultdict
default_factory 是 __missing__() 方法使用的 defaultdict 構(gòu)造函數(shù)的第一個(gè)參數(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
正如我們?cè)谏厦娴氖纠锌吹降?,字?dic 中有兩對(duì)數(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ù)制到另一個(gè)我們可以相應(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ù)有兩個(gè)參數(shù),第一個(gè)是鍵,第二個(gè)是鍵的默認(rèn)值,以防該值不存在。
但第二個(gè)參數(shù)是可選的。 所以我們可以指定任何消息或值; 否則,它將顯示 None 作為默認(rèn)值。
以上就是詳解Python中defaultdict的具體使用的詳細(xì)內(nèi)容,更多關(guān)于python defaultdict的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python實(shí)現(xiàn)圖片指定位置加圖片水?。ǜ絇yinstaller打包exe)
這篇文章主要介紹了Python實(shí)現(xiàn)圖片指定位置加圖片水印,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03Python大數(shù)據(jù)之使用lxml庫(kù)解析html網(wǎng)頁(yè)文件示例
這篇文章主要介紹了Python大數(shù)據(jù)之使用lxml庫(kù)解析html網(wǎng)頁(yè)文件,結(jié)合實(shí)例形式分析了Python大數(shù)據(jù)操作中使用lxml庫(kù)解析html網(wǎng)頁(yè)具體步驟及相關(guān)注意事項(xiàng),需要的朋友可以參考下2019-11-11Python中read,readline和readlines的區(qū)別案例詳解
這篇文章主要介紹了Python中read,readline和readlines的區(qū)別案例詳解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09Python使用SQLAlchemy模塊實(shí)現(xiàn)操作數(shù)據(jù)庫(kù)
SQLAlchemy 是用Python編程語言開發(fā)的一個(gè)開源項(xiàng)目,它提供了SQL工具包和ORM對(duì)象關(guān)系映射工具,使用SQLAlchemy可以實(shí)現(xiàn)高效和高性能的數(shù)據(jù)庫(kù)訪問,下面我們就來學(xué)習(xí)一下SQLAlchemy模塊的具體應(yīng)用吧2023-11-11django 前端頁(yè)面如何實(shí)現(xiàn)顯示前N條數(shù)據(jù)
這篇文章主要介紹了django 前端頁(yè)面如何實(shí)現(xiàn)顯示前N條數(shù)據(jù)。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03