Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary Looping

As you will understand from my question, I am new to programming and as most people who are new to this, I am having issues comprehending some of the code. I came across the following code in Python which translates some words from German to English and returns a string of the translation:

deu2eng = {
'ich':'I',
'gehe':'go',
'nach':'to',
'die':'the',
'kirche':'church'}

def trans(eng2deu):
    translation = ''
    for word in eng2deu.split():
        if word in deu2eng:
            translation+= deu2eng[word] + ' '
        else:
            translation += word + ' '
    return translation

When I run the following it works: trans('ich gehe nach die kirche')

However there are some issues. I can't get to understand how I can get it to be case insensitive (e.g. if I type Kirche instead of kirche, it will return Kirche instead of church). I tried using the lower() method to no avail. But most importantly, I do not understand the following line and why it works:

translation+= deu2eng[word] + ' '

From what you can infer, this is quite basic, but I would like to fully comprehend what is happening with this code as I am stuck in the 2 aforementioned things.

like image 253
Seifer Avatar asked Apr 12 '26 20:04

Seifer


1 Answers

To make it case-insensitive, change the for line to:

for word in lower(eng2deu).split()

Here's the step-by-step explanation of translation+= deu2eng[word] + ' ':

  1. Get the translation of word from the deu2eng dictionary.
  2. Concatenate a space to the end of that.
  3. Set translation to the concatenation of translation and that string.

Remember that x += y is just short for x = x + y. So

translation+= deu2eng[word] + ' '

means

translation = translation + deu2eng[word] + ' '
like image 98
Barmar Avatar answered Apr 15 '26 11:04

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!