python字典中的多个键和值

2024-06-16 09:54:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用kivy(python)制作考试应用程序,我在获得正确答案方面遇到了问题。我有从拉丁语单词到斯洛文尼亚语单词的口述翻译示例(键是拉丁语单词,值是斯洛文尼亚语单词):

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

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

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

例如:

Exemple_pic

在你们看到的应用程序的图片上,我必须翻译“Agito”是什么意思“stresam”,所以我的问题是如何检查它的多个键,它的值是什么

我希望你能理解我的问题:)


Tags: 答案应用程序示例ab单词kivyoddic
3条回答

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

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

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
        ...

相关问题 更多 >