Idont Reallywolf Idont Reallywolf - 6 months ago 16
Python Question

Python function returns empty list

I've been working on this task for a while, the task is to write a function that translated a text in english to swedish. I've created a dicitonary with key & value, where key is the english word and value is the swedish word.

I was thinking of that there should be 2 for loops. First one should iterate thru keys and values in the dictionary, and the second one should iterate thru the string, after that there should be a condition where it checks if key in the dictionary is equals to the word in the string.
if so, append the value of the key to the list.

The function returns an empty list.


def translate(a):
trs = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"}
translated = []
for k, v in trs.iteritems():
for i in a.split(" "):
if trs[k] == i:
return translated

print translate("merry christmas and happy new year")


There are multiple problems with your code.

The first one is that you iterate over the key-value pairs in the dictionary, and later try to use the values as keys here: if trs[k] == i: and here translated.append(trs[v]) These should be just k and v instead of trs[k] and trs[v].

The second problem is a bigger one: after fixing the previous, the code still gives wrong answer. The words are in random order. This is because you iterate over the dictionary items in the outer loop instead of the words themselves. This can easily be fixed by changing the order of the loops.

The third is that I think the function should return a string. Just return " ".join(translated) at the end.

And the fourth is that you actually don't use the dictionary as a dictionary. You use it as a list, but it's not how they are meant to be used. dicts are direct mappings of values, you don't need to iterate over all the entries all the time. Use the in and [] operators.

So here is how this code should look like:

def translate(a):
    trs = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"ar"}
    translated = []
    for i in a.split(" "): 
      if i in trs:
    return " ".join(translated)

print translate("merry christmas and happy new year")
# prints "god jul och gott nytt ar"