簡體   English   中英

Python defaultdict(default) vs dict.get(key, default)

[英]Python defaultdict(default) vs dict.get(key, default)

假設我想創建一個dict (或類似dict的對象),如果我嘗試訪問不在dict中的鍵,則返回默認值。

我可以通過使用defaultdict來做到這一點:

from collections import defaultdict

foo = defaultdict(lambda: "bar")
print(foo["hello"]) # "bar"

或通過使用常規dict並始終使用dict.get(key, default)來檢索值:

foo = dict()
print(foo.get("hello", "bar")) # "bar"
print(foo["hello"]) # KeyError (as expected)

除了必須記住使用帶有默認值而不是預期的括號語法的.get()明顯的人體工程學開銷之外,這兩種方法之間有什么區別?

除了.get每個人的人體工程學之外,一個重要的區別是,如果您在defaultdict中查找缺少的鍵,它將向自身插入一個新元素,而不僅僅是返回默認值。 最重要的影響是:

  • 稍后的迭代將檢索在defaultdict中查找的所有鍵
  • 隨着更多最終存儲在字典中,通常使用更多 memory
  • 默認值的突變會將該突變存儲在defaultdict中,除非存儲明確,否則.get默認值會丟失
from collections import defaultdict 
 
default_foo = defaultdict(list) 
dict_foo = dict()                                                                                                                                                                                                                                                                                           

for i in range(1024): 
    default_foo[i] 
    dict_foo.get(i, []) 
                                                                                                                                                                                                                                                                                                 
print(len(default_foo.items())) # 1024
print(len(dict_foo.items())) # 0

# Defaults in defaultdict's can be mutated where as with .get mutations are lost
default_foo[1025].append("123")
dict_foo.get(1025, []).append("123")

print(default_foo[1025]) # ["123"]
print(dict_foo.get(1025, [])) # []

這里的區別實際上歸結為您希望程序如何處理 KeyError。

foo = dict()

def do_stuff_with_foo():
    print(foo["hello"])
    # Do something here
   
if __name__ == "__main__":
    try:
        foo["hello"] # The key exists and has a value
    except KeyError:
        # The first code snippet does this
        foo["hello"] = "bar"
        do_stuff_with_foo()

        # The second code snippet does this
        exit(-1)

問題是我們要完全停止該程序嗎? 我們是希望用戶為 foo["hello"] 填寫一個值還是要使用默認值?

第一種方法是一種更緊湊的方式來執行foo.get("hello", "bar")但關鍵在於這是我們真正想要發生的事情嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM