python字典中的多个键和值



我正在用kivy(python(制作Exam应用程序,但我无法获得正确答案。我有从拉丁单词翻译成斯洛文尼亚单词的dictionary示例(键是拉丁单词,值是斯洛文尼亚单词(:

Dic = {"Aegrotus": "bolnik", "Aether": "eter"}

所以问题是,当2或3个拉丁单词的意思与1个斯洛文尼亚单词的意思相同时,反之亦然。示例:

Dic = {("A", "ab"): "od", "Acutus": ("Akuten", "Akutna", "Akutno"), "Aromaticus": ("Dišeč", "Odišavljen")}

例如:

示例_ pic

在你看到的应用程序上,我必须翻译"Agito"的意思是"stresam",所以我的问题是如何检查它的多个键,它的值是多少。

我希望你能理解我的问题:(。

首先,您必须能够从图片中显示的应用程序中获得文本输出,然后使用字典进行检查。

而且字典的设计方式使检查变得困难。您应该这样设计:键只是一个字符串,值是一个列表。例如:

Dic = {"A": ["od"], "ab": ["od"], "Acutus": ["Akuten", "Akutna", "Akutno"], "Aromaticus": ["Dišeč", "Odišavljen"]}

所以现在,当你从应用程序中获得文本后,假设它是text = 'ab:id'。你将把它分成密钥和值,然后检查你的dict:

def check(text):
text = text.split(':')
key = text[0]
value = text[1]
if value in Dic[key]:
return True
return False

让我们试试

>>> check('ab:id')
False
>>> check('ab:od')
True
>>> check('Acutus:Akutna')
True
>>> check('Acutus:Akutno')
True

你只需要翻译拉丁语->斯洛文尼亚语而不需要翻译其他语言吗?如果是这样的话,就把每一个键都做成一个单词。多个键具有相同的值是可以的:

Dic = {
"Aegrotus": "bolnik", "Aether": "eter", "A": "od", "ab": "od",
"Acutus": ("Akuten", "Akutna", "Akutno"), "Aromaticus": ("Dišeč", "Odišavljen"),
}

每次查找if then的形式为Dic[latin] -> slovenian,其中latin是单个单词,slovenian是一个或多个单词。

您可以使用dict.items()(dict.iteritems()用于python2,但我为什么要提到这一点?(

所以试试

for latin_words, slovenian_words in dic.items():
if isinstance(latin_words, tuple):
# this is the check
# if there are multiple values
# this will run
...
if isinstance(slovenian_words, tuple):
# this is the check
# if there are multiple values
# this will run
...

如果您想双向搜索,在权衡内存使用率和搜索速度的基础上,您可以考虑构建第二个反向字典。我修改了你的例子,在第一个字典中有唯一的拉丁键,然后创建了第二个字典,它的结构略有不同(不能添加到元组中,所以使用集合(,但应该以与第一个相同的方式进行搜索。

from collections import defaultdict
Dic = {"A": "od", "ab": "od", "Acutus": ("Akuten", "Akutna", "Akutno"), "Aromaticus": {"Dišeč", "Odišavljen"}}
Dic2 = defaultdict(set)
for k, v in Dic.items():
if isinstance(v, str):   # just one translation
Dic2[v].add(k)
else:                    # more than one translation, given as a tuple
for i in v:
Dic2[i].add(k)
#print(Dic)
#print(Dic2)

最新更新