I've to write a function that takes a list of English words and returns a list of Swedish words. For example, {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"år"} used to translate English into Swedish.

def translate(a):
  a = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"}

  for k, v in a.iteritems():
    print k,v
translate(a)

But this does not give any output. Please advise.

Recommended Answers

All 2 Replies

One possibility:

def translate(text, e_s_dict):
    swed = ""
    space = " "
    for word in text.split():
        swed += e_s_dict[word] + space
    return swed


# english:swedish dictionary
e_s_dict = {"merry":"god",
"christmas":"jul",
"and":"och",
"happy":"gott",
"new":"nytt",
"year":"år"}

# english text
eng_text = "merry christmas"

# translate to swedish text
swed_text = translate(eng_text, e_s_dict)
print(swed_text)  # result --> god jul

Use meaningful variable names. It will help you understand what is going on.

To fix your orginal code.

def translate():
    a = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"}
    return a

for k, v in translate().iteritems():
    print k, v

You need to practice more on using functions.
It make no sense to take a argument a,when all you have in function is a dicionary.
a as mention is not a meaningful variable name.

Something like this for translate.

def my_dict(user_input):
    return {
    "merry": "god",
    "christmas": "jul",
    "and": "och",
    "happy": "gott",
    "new": "nytt",
    "year": "år"
     }.get(user_input, "Not in dicionary")

def translate(word):
    return my_dict(word)

Test:

>>> translate('christmas')
'jul'
>>> translate('hello')
'Not in dicionary'
>>> translate('happy')
'gott'
>>> print '{} {} til alle i Sverige'.format(translate('merry'), translate('christmas'))
god jul til alle i Sverige
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.