Python 检查嵌套字典中的两个内部键是否重复,并仅检索最高值

Python 检查嵌套字典中的两个内部键是否重复,并仅检索最高值,python,dictionary,Python,Dictionary,我有一个嵌套字典,如下所示: d = {'DET':{'this':0.5, 'the':0.4}, 'NOUN': {'cat':0.8, 'can':0.2}, 'VERB': {'can':0.6, 'fly':0.3}...} sent = ['the', 'cat', 'can', 'fly'] found = {} for k, v in d.items(): for token in sent: if token in v: if

我有一个嵌套字典,如下所示:

d = {'DET':{'this':0.5, 'the':0.4}, 'NOUN': {'cat':0.8, 'can':0.2}, 'VERB': {'can':0.6, 'fly':0.3}...}
sent = ['the', 'cat', 'can', 'fly']
found = {}
for k, v in d.items():
    for token in sent:
        if token in v:
            if v[token] > found.get(token, {}).get('val', 0):
                found[token] = {'type': k, 'val': v[token]}
给定一个令牌列表,我想检查这些令牌是否都在字典中,并检索其值和父键。如果存在歧义,我可以为每个令牌设置多个父密钥(在我的示例中,“can”是名词,但也是动词),并且我只希望获取令牌具有最高值的父密钥

到目前为止,我已经:

sent = ['the', 'cat', 'can', 'fly']
for k, v in d.items():
    for token in sent:
        if token in d[k]:
            print token, k, v[token]
这为每个标记提供了所有可能的标记和相关值

cat NOUN 0.8
can NOUN 0.2
can VERB 0.6
fly VERB 0.3
the DET 0.4
但在“可以”的情况下,我只想

can VERB 0.6

所以不要马上打印它们;将它们存储在字典中,当相同的大小写再次出现时,只保留值最高的版本。当你扫描完
d
后,你可以浏览这本词典并打印出其中的内容。

我会这样做:

d = {'DET':{'this':0.5, 'the':0.4}, 'NOUN': {'cat':0.8, 'can':0.2}, 'VERB': {'can':0.6, 'fly':0.3}...}
sent = ['the', 'cat', 'can', 'fly']
found = {}
for k, v in d.items():
    for token in sent:
        if token in v:
            if v[token] > found.get(token, {}).get('val', 0):
                found[token] = {'type': k, 'val': v[token]}
现在发现的是:

{'can': {'type': 'VERB', 'val': 0.6},
 'cat': {'type': 'NOUN', 'val': 0.8},
 'fly': {'type': 'VERB', 'val': 0.3},
 'the': {'type': 'DET', 'val': 0.4}}

这将打印每个标记具有最高值的所有标记(如果同时存在“can动词0.6”和“can名词0.6”):

第一个循环使用
defaultdict
收集每个标记的相同值的所有标记,这是创建嵌套字典结构的简单方法。对于每个标记,它存储一个字典,将值映射到标记集


第二个循环使用元组(字典项)主要在其第一个元素(字典键,即与所讨论的标记相关联的值)上排序的事实,将重新构造的数据减少为仅最大值。

谢谢,我将使用您的答案,它看起来最适合我的需要。