[英]Python's collections.defaultdict returns default value correctly unless the key isn't referenced first
[英]defaultdict with tuple as the key, how to set default value in the event key isn't found
假設我有以下格式的defaultdict
:
theta = defaultdict(float)
鍵由一個字符串元組(即(label, word)
,並且關聯的值是給定單詞適合給定標簽的概率(語音標記的一部分)。
例如,單詞“ stand”可以是名詞或動詞。 所以我可以做類似的事情:
theta[('NOUN', 'stand')] = 0.4
theta[('VERB', 'stand')] = 0.6
theta[('ADJ', 'stand')] = 0.0
對於語音標簽的其余部分,依此類推。
我需要做的是讓字典在默認情況下返回值1(如果它使用不包含該詞的單詞調用並且關聯的標簽為“ NOUN”),則默認為1,對於所有其他關聯的標簽返回0。 例如:
value = theta[('NOUN', 'wordthatdoesntexist')] # this should be 1
value = theta[('VERB', 'wordthatdoesntexist')] # this should be 0
我怎樣才能做到這一點? 我可以在初始化步驟中使用lambda嗎? 還是有其他方法?
defaultdict無法做到這一點; 默認工廠無權訪問密鑰。 當您嘗試訪問丟失的密鑰時,必須使用__missing__
鈎子字典來編寫自己的dict子類:
class SomeAppropriateName(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __missing__(self, key):
val = 1.0 if key[0] == 'NOUN' else 0.0
# Uncomment the following line if you want to add the value to the dict
# self[key] = val
return val
您可以使用dict
的setdefault()
方法:
d.setdefault(u, int(u[0] == "NOUN"))
如果在d
找到u
,則setdefault返回d[u]
。 否則,將其插入dict中,並使用提供的值作為第二個參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.