[英]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
中查找的所有鍵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.