如何根据给定值打印字典中的键

0 投票
2 回答
604 浏览
提问于 2025-04-18 10:37

这是我一个字典,里面有单词和它们的定义:

Vocab={'Precaution' : "a measure taken in advance to avert possible evil or to secure good results",
'Cautious' : "showing, using, or characterized by caution",
'Cautionary' : "of the nature of or containing a warning",
'Dissuade' : "to deter by advice or persuasion; persuade not to do something",
'Persuasion' : "the act of persuading or seeking to persuade"}

这是另一个字典,不过这个字典的键是拉丁词根,值是相关的词汇。

 Roots={'Caut' :{'Precaution', 'Catious', 'Cautionary'}, 'Saud' :{'Dissuade', 'Persuasion'}}

现在这是一个小测验游戏:

print "If you want to know the root of the word, type 'root'"
while 1:
    y = random.choice(Vocab.keys())
    print y
    t2=raw_input("What is the definition?: ")
    if t2 in Vocab[y]:
        print 'All those words were in the definition!'
        print Vocab[y]
    elif t2 not in Vocab[y]:
        if t2 == 'root':
            print Roots
        elif t2 != 'root':
            for key,y in Roots.iteritems()):
                print key

我想让用户输入“根”,然后显示这个根作为提示。根显示出来后,屏幕上会出现同样的问题单词,让他尝试回答。当用户输入“根”时,整个字典会显示出来。我该怎么做才能打印出这个单词的词根呢?

2 个回答

1

我不太确定你需要什么,但为什么不把词根直接和主要的词汇放在一个数据结构里呢?这样就可以很方便地打印出当前单词的词根,而不需要用到反向字典或者其他查找方法。

vocab = {
    'Precaution' : {'root': 'Caut', 'def': 'definition': 'a measure ...'},
    'Cautious'   : {'root': 'Caut', 'def': 'showing, using, ...'},
    'Dissuade'   : {'root': 'Saud', 'def': 'to deter ...'},
}

这种方法也符合面向对象的设计,如果将来你的问题需要朝这个方向发展,每个 Word 实例都可以包含它相关的属性,比如定义、词根、不同的拼写方式等等。

举个例子:

wroots = { w : r for r, ws in Roots.iteritems() for w in ws }
vocab  = { w : dict(root = wroots[w], defin = d) for w, d in Vocab.iteritems() }
2

建议1:找出这个输入单词在值里面的键值对,然后打印出对应的键。

if t2 == 'root':
    for root,words in Roots.iteritems():
        if y in words:
            print root
            break

建议2:创建这个字典

invRoots = {word:root for root,words in Roots.iteritems() for word in words}

然后使用

if t2 == 'root':
    print invRoots[y]

还有一件事:你的 Roots 里面有个拼写错误:'Catious'

撰写回答