简体   繁体   中英

Python- Lists to Dictionary

I am new to learning python and I am working on a mini translator that translates English to Spanish and Spanish to English. There is a option for users to type in 'show' to see either the English or Spanish List.

Could someone help me understand why this doesn't translate the word when they type in either of the English or Spanish words that are in the list. When I say it doesn't translate, nothing happens and I can just keep typing in new words and it does nothing. The 'show' part works correctly though.

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:
            translate(word)
        except Exception as e:
            print ("That wasn't a option")

Any help would be appreciated. Thanks

You are returning the word from translate but never printing it. Change your line towards the end (inside the try ) to print(translate(word)) .

In Python, dictionary is created with 'key-value pairs' like below.

dict = {"fire":"fuago", "apple":"manzana" ...}

In your code, you use zip function which generates list of tapples from tapple of list. So your code like below (after zip function executed)

dict = {("fire","fuago"),("apple","manzana") ...}

You use tapples instead of key-value pairs is main reason of your problem, I guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM