Python 中的defaultdict

字典是 Python 中數據值的無序集合,用於存儲數據值,如地圖。字典保存鍵值對,而不是像其他數據類型一樣保存單個值作為元素。字典中實現的鍵必須是唯一且不可變的。也就是說,Python 元組可以是關鍵字,但是 Python 列表不能是字典中的關鍵字。我們可以通過在花括號{}內放置一系列元素來創建字典,逗號“,”可以分隔值。


Dict_1 = {1: 'A', 2: 'B', 3: 'C', 4: 'D'}
print ("Dictionary: ")
print (Dict_1)
print ("key pair 1: ", Dict_1[1])
print ("key pair 3: ", Dict_1[3])

輸出:

Dictionary: 
{1: 'A', 2: 'B', 3: 'C', 4: 'D'}
key pair 1: A
key pair 3: C

但是如果我們試圖打印第五個鍵值,那麼我們會得到錯誤,因為“Dict _ 1”不包含第五個鍵值。


Dict_1 = {1: 'A', 2: 'B', 3: 'C', 4: 'D'}
print ("Dictionary: ")
print (Dict_1)
print ("key pair 5: ", Dict_1[5])

輸出:

Dictionary: 
{1: 'A', 2: 'B', 3: 'C', 4: 'D'}
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
 in <module>2 print ("Dictionary: ")
      3 print (Dict_1)
----> 4 print ("key pair 5: ", Dict_1[5])

KeyError: 5</module> 

每當鍵錯誤出現時,就可能成為用戶的問題。我們可以通過使用 Python 的另一個字典來克服這個錯誤,它就像一個名為 Defaultdict 的容器。用戶可以在“收藏”模塊中找到這本字典。

defaultdict 是 Python 的字典,它就像一個容器,存在於“集合”模塊中。它是字典類的一個子類,用於返回類似字典的對象。defaultdict 和字典具有相同的功能,除了 defaultdict 從不引發任何鍵錯誤,因為它為鍵提供了默認值,而該默認值不存在於用戶創建的字典中。

語法:


defaultdict(default_factory)

參數:

  • default _ factory:default _ factory()函數返回用戶為自己定義的字典設置的默認值。如果這個參數不存在,那麼字典將引發鍵錯誤。

示例:


from collections import defaultdict as DD
# Function for returning a default values for the
# keys which are not present in the dictionary
def default_value():
    return "This key is not present"

# Now, we will define the dict
dict_1 = DD(default_value)
dict_1["ABC"] = 1
dict_1["DEF"] = 2
dict_1["GHI"] = 3
dict_1["JKL"] = 4
print ("Dictionary: ")
print (dict_1)
print ("key pair 1: ", dict_1["ABC"])
print ("key pair 3: ", dict_1["GHI"])
print ("key pair 5: ", dict_1["MNO"])

輸出:

Dictionary: 
defaultdict(, {'ABC': 1, 'DEF': 2, 'GHI': 3, 'JKL': 4})
key pair 1:  1
key pair 3:  3
key pair 5:  This key is not present 

當我們使用 defaultdict 時,除了標準的字典操作之外,我們還獲得了一個額外的可寫實例變量和一個方法。可寫實例變量是默認的 _factory 參數, missing 是方法。

  • default _ factory:default _ factory()函數返回用戶為自己定義的字典設置的默認值。

示例:


from collections import defaultdict as DD
dict_1 = DD(lambda: "This key is not present")
dict_1["ABC"] = 1
dict_1["DEF"] = 2
dict_1["GHI"] = 3
dict_1["JKL"] = 4
print ("Dictionary: ")
print (dict_1)
print ("key value 1: ", dict_1["ABC"])
print ("key value 3: ", dict_1["GHI"])
print ("key value 5: ", dict_1["MNO"])

輸出:

Dictionary: 
defaultdict( at 0x0000019EFC4B58B0>, {'ABC': 1, 'DEF': 2, 'GHI': 3, 'JKL': 4})
key value 1:  1
key value 3:  3
key value 5:  This key is not present 
  • missing (): missing ()函數用於為字典提供默認值。missing()函數將 default_factory 作為參數,如果該參數設置為 None,將引發 KeyError 否則,它將為給定的鍵提供默認值。當沒有找到請求的密鑰時,這個方法實際上是由 dict 類的 getitem() 函數調用的。getitem()函數提升或返回 missing()函數中的值。

示例:


from collections import defaultdict as DD
dict_1 = DD(lambda: "This key is not present")
dict_1["ABC"] = 1
dict_1["DEF"] = 2
dict_1["GHI"] = 3
dict_1["JKL"] = 4
print ("Dictionary: ")
print (dict_1)
print ("key value 1: ", dict_1.__missing__('ABC'))
print ("key value 4: ", dict_1["JKL"])
print ("key value 5: ", dict_1.__missing__('MNO'))

輸出:

Dictionary: 
defaultdict( at 0x0000019EFC4B5670>, {'ABC': 1, 'DEF': 2, 'GHI': 3, 'JKL': 4})
key value 1:  This key is not present
key value 4:  4
key value 5:  This key is not present 

我們可以傳遞一個 list 類作為 default_factory 參數,它將使用以 list 格式設置的值創建一個 defaultdict。

示例:


from collections import defaultdict as DD
# Defining a dictionary
dict_1 = DD(list)

for k in range(7, 12):
    dict_1[k].append(k)

print ("Dictionary with values as list:")
print (dict_1)

輸出:

Dictionary with values as list:
defaultdict(<class 'list'>, {7: [7], 8: [8], 9: [9], 10: [10], 11: [11]})

我們可以將 int 類作為 default_factory 參數傳遞,它將創建一個默認值設置為零的 defaultdict。

示例:


from collections import defaultdict as DD

# Defining the dict
dict_1 = DD(int)

J = [1, 2, 3, 4, 2, 4, 1, 2]

# Now, we will iterate through the list "J"
# for keeping the count
for k in J:

    # As, The default value is 0
    # so we do not need to
    # enter the key first
    dict_1[k] += 1

print(dict_1)

輸出:

defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})

在本教程中,我們討論了 Python 中的 defaultdict,以及如何使用 default_factory 參數對 defaultdict 執行不同的操作。


原創文章,作者:D7PGM,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/127023.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
D7PGM的頭像D7PGM
上一篇 2024-10-03 23:13
下一篇 2024-10-03 23:13

相關推薦

  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python編程二級證書考試相關現已可以上網購買

    計算機二級Python考試是一項重要的國家級認證考試,也是Python編程的入門考試。與其他考試一樣,Python編程二級證書的考生需要進入正式考試,而為了備考,這篇文章將詳細介紹…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29

發表回復

登錄後才能評論