首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >迭代字典中的值以反演键和值

迭代字典中的值以反演键和值
EN

Stack Overflow用户
提问于 2017-12-08 09:23:11
回答 1查看 26关注 0票数 0

我正试图用下面的代码反演一本意大利语-英语词典。

有些术语有一个翻译,而另一些则有多种可能。如果一个条目有多个翻译,我会遍历每个单词,并将其添加到英语-意大利语词典(如果还没有出现)。

如果有一个单独的翻译,它不应该迭代,但正如我已经编写的代码,它是。此外,在词典中只添加了包含多个翻译的术语中的最后一个翻译。我不知道如何重写代码来解决什么应该是真正简单的任务。

代码语言:javascript
复制
from collections import defaultdict

def invertdict():
    source_dict ={'paramezzale (s.m.)': ['hog', 'keelson', 'inner keel'], 'vento (s.m.)': 'wind'}

    english_dict = defaultdict(list)

    for parola, words in source_dict.items():
        if len(words) > 1: # more than one translation ?
            for word in words: # if true, iterate through each word
                word = str(word).strip(' ')
                print(word)
        else: # only one translation, don't iterate!!
            word = str(words).strip(' ')
            print(word)
        if word in english_dict.keys(): # check to see if the term already exists
            if english_dict[word] != parola: # check that the italian is not present 
                #english_dict[word] = [english_dict[word], parola]
                english_dict[word].append(parola).strip('')
        else:
           english_dict[word] = parola.strip(' ')

    print(len(english_dict)) 

    for key,value in english_dict.items():
       print(key, value)

当运行此代码时,我得到:

代码语言:javascript
复制
hog
keelson
inner keel
w
i
n
d
2
inner keel paramezzale (s.m.)
d vento (s.m.)

而不是

代码语言:javascript
复制
hog: paramezzale, keelson: paramezzale, inner keel: paramezzale, wind: vento
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-08 09:34:26

在字典中的任何地方使用列表都会更容易,例如:

代码语言:javascript
复制
source_dict = {'many translations': ['a', 'b'], 'one translation': ['c']}

然后需要2个嵌套循环。现在你并不总是在运行内环。

代码语言:javascript
复制
for italian_word, english_words in source_dict.items():
    for english_word in english_words:
        # print, add to english dict, etc.

如果无法更改source_dict格式,则需要显式检查类型。我会转换列表中的单个项目。

代码语言:javascript
复制
for italian_word, item in source_dict.items():
    if not isinstance(item, list):
        item = [item]

完整代码:

代码语言:javascript
复制
source_dict ={'paramezzale (s.m.)': ['hog', 'keelson', 'inner keel'], 'vento (s.m.)': ['wind']}

english_dict = defaultdict(list)

for parola, words in source_dict.items():
    for word in words:
        word = str(word).strip(' ')
        # add to the list if not already present
        # english_dict is a defaultdict(list) so we can use .append directly
        if parola not in english_dict[word]: 
               english_dict[word].append(parola)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47711187

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档