以元组为键的defaultdict,未找到如何在事件键中设置默认值

use*_*193 1 python dictionary tuples defaultdict

假设我有defaultdict以下形式:

theta = defaultdict(float)
Run Code Online (Sandbox Code Playgroud)

键由字符串元组 ie 组成(label, word),相关值是给定单词适合给定标签(词性标注)的概率。

例如,“stand”这个词可以是名词或动词。所以我可以做这样的事情:

theta[('NOUN', 'stand')] = 0.4
theta[('VERB', 'stand')] = 0.6
theta[('ADJ', 'stand')] = 0.0
Run Code Online (Sandbox Code Playgroud)

对于语音标签的其余部分,依此类推。

我需要做的是让字典在默认情况下返回 1 的值,如果它是用它不包含的单词调用的,并且关联的标签是“NOUN”,并为所有其他关联的标签返回 0。例如:

value = theta[('NOUN', 'wordthatdoesntexist')]  # this should be 1
value = theta[('VERB', 'wordthatdoesntexist')]  # this should be 0
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?我可以在初始化步骤中使用 lambda 来完成吗?或者有其他方法吗?

use*_*ica 5

defaultdict 不能这样做;默认工厂无权访问密钥。您必须编写自己的 dict 子类,__missing__当您尝试访问丢失的密钥时,使用钩子 dicts 查找:

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
Run Code Online (Sandbox Code Playgroud)