list - How to translate english to swedish using dictionary in python -


i using following code, showing error - index out of range

english=["merry", "christmas", "and", "happy", "new", "year"] swedish=["god","jul","och","gott","nytt","år"] dict = {english[n]: swedish[n] n in range(len(english))}#dictionary trans_list=[]#list save translated words  def trans(list):     n=0     word1 in list:             word2 in english:              if word1==word2:                                     trans_list[n]=dict[word2]                        n=n+1                        print trans_list                  list2=[] list =["merry", "christmas", "and", "happy", "new", "year"] trans(list) 

here approach problem:

english = ["merry", "christmas", "and", "happy", "new", "year"] swedish = ["god", "jul", "och", "gott", "nytt", "år"]  eng_swe_dict = {english: swedish english, swedish in zip(english, swedish)}  def trans(word_list):     return [eng_swe_dict[word] word in word_list]  word_list = ["merry", "christmas", "and", "happy", "new", "year"] print trans(word_list) 

this display following:

['god', 'jul', 'och', 'gott', 'nytt', 'år'] 

firstly, should avoid using variable names such dict , list these built in python commands. python not complain, reassign meaning.

your lookup dictionary constructed using zip command. in case, takes 1 entry each of 2 lists provide loop, used construct dictionary.

a python list comprehension can used create translated list. each word, translates , adds new list.


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -