【问题标题】:Importing Dictionaries导入字典
【发布时间】:2017-08-03 16:22:49
【问题描述】:
english_list = ["fire","apple","morning","river","wind"]
spanish_list = ["fuego","manzana","mañana","río","viento"]
english_to_spanish = dict(zip(english_list, spanish_list))
spanish_to_english = dict(zip(spanish_list, english_list))

def translate(word):
    translation = english_to_spanish.get(word)
    if translation:
        return translation

    translation = spanish_to_english.get(word)
    if translation:
        return translation

    raise Exception('Word {0} does not exists'.format(word))

print("Welcome to the English <--> Spanish Dictionary")
while True:
    word = input("> ")
    if word == 'show':
        wordlist = input("Would you like to see the English or Spanish wordlist?")
        if wordlist == 'english':
            print(english_list)
        elif wordlist == 'spanish':
            print(spanish_list)
    else:
        try:
            print(translate(word))
        except Exception as exeception:
            print ("That wasn't a option")

这是我的代码,我想导入一个字典(我有),但我不知道该怎么做,我对编码很陌生,真的需要一些帮助,这是一个学校作业,我真的需要帮助,任何帮助将不胜感激!

【问题讨论】:

  • 您要导入的字典的格式是什么?
  • 通过导入,您的意思是您有一个包含单词对(英语与西班牙语配对)的文件?或者正如您的示例所暗示的那样,您有两个单独的文件,其中包含英语单词和西班牙语单词列表?

标签: python python-3.x dictionary


【解决方案1】:

如果你想从 json 文件中导入你的字典,你可以这样做

import json

json_path = 'your_json_file.json'
with open(json_path) as json_data:
    your_dictionary = json.load(json_data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-23
    • 2017-12-04
    • 1970-01-01
    • 2012-04-19
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多