Translation using dictionaries

I'm just trying to use some code from books, and there are different exercises, but I wanted to try one with an existing message, I got this far, but I can’t figure out how to complete it. How can i do this?

alphabet = {"A": ".-","B": "-...","C": "-.-.",
            "D": "-..","E": ".","F": "..-.",
            "G": "--.", "H": "....","I": "..",
            "J": ".---","K": "-.-", "L": ".-..",
            "M": "--",  "N": "-.",  "O": "---",
            "P": ".--.","Q": "--.-","R": ".-.",
            "S": "...", "T": "-",   "U": "..-",
            "V": "...-","W": ".--", "X": "-..-",
            "Y": "-.--", "Z": "--.."}

message = ".-- .... . .-. . / .- .-. . / -.-- --- ..-"

for key,val in alphabet.items():
    if message in alphabet:
        print(key)
+6
source share
2 answers

You need to cancel the dictionary:

alphabet1 = {b:a for a, b in alphabet.items()} 
message = ".-- .... . .-. . / .- .-. . / -.-- --- ..-"
decoded_message = ''.join(alphabet1.get(i, ' ') for i in message.split())

Output:

'WHERE ARE YOU'
+5
source

The main problem is that you need to split the message into separate parts that can be decoded separately.

The message is first separated by slashes (words), and then by spaces (characters). Therefore, we can use split()twice here to get the elements:

for word in message.split('/'):
    for character in word.strip().split():
        # ... decode the character

- . : , , .

:

decode_dict = {v: k for k, v in alphabet.items()}

, :

decode_dict = {v: k for k, v in alphabet.items()}

for word in message.split('/'):
    for character in word.strip().split():
        print(decode_dict[character])  # print the decoded character
    print(' ')  # print space after the word

, . str.join :

' '.join(''.join(decode_dict[character] for character in word.strip().split())
         for word in message.split('/'))

:

>>> ' '.join(''.join(decode_dict[character] for character in word.strip().split())
...          for word in message.split('/'))
'WHERE ARE YOU'
+7

All Articles