[英]Writing code for dict and defaultdict
我有以下問題:
from collections import defaultdict
def give_it_to_me(d):
# This will crash if key 'it' does not exist
return d['it']
def give_it2_to_me(d):
# This will never crash, but does not trigger the default value in defaultdict
return d.get('it2')
d1 = defaultdict(int)
d2 = { 'it' : 55 }
print give_it_to_me(d1)
print give_it_to_me(d2)
print give_it2_to_me(d1)
print give_it2_to_me(d2)
正如您在評論中看到的那樣,編寫一個give_it_to_me
版本似乎是不可能的:
defaultdict
的默認值 還是我錯了?
您可能需要在give_it_to_me
函數中添加更多代碼。
使用try
except
語句檢查現有密鑰。
例如:
def give_it_to_me(d):
# This won't crash if key 'it' does not exist in a normal dict.
# It returns just None in that case.
# It returns the default value of an defaultdict if the key is not found.
try:
return d['it']
except KeyError:
return None
使用try .. except
:
try
return d['it']
except KeyError:
return None
為什么defaultdict.get
無法按預期工作 :
defaultdict
使用__missing__方法實現。 當密鑰k
不在字典中時, dict.__getitem__(k)
__missing__
方法僅由dict[k]
(或dict.__getitem__(k)
) dict.__getitem__(k)
。
請注意,除
__getitem__()
之外的任何操作都不會調用__missing__()
__getitem__()
。 這意味着get()
將像普通字典一樣,返回None作為默認值,而不是使用default_factory
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.