Skip to content Skip to sidebar Skip to footer

Using Dictionary And Printing Out Value When Matched Key And Vise-versa

I have a dictionary where the key is a letter in the alphabet and it’s value is its corresponding Morse code letter (e.g. ”A”: “.-“). I also have a user input where the u

Solution 1:

For translating text to morse, just map the characters of the string to the corresponding value from the translation dictionary:

>>>msg = "HELLO WORLD">>>morse = ' '.join(map(translation.get, msg))>>>morse
'.... . .-.. .-.. ---    .-- --- .-. .-.. -..'

Note that I separated the codes with spaces, otherwise it will be nearly impossible to decode the message back, as some sequences could yield in different combinations of characters. For the translation back, you first have to inverse the dictionary; then split the morse message by space and get the value from the inverse dictionary.

>>>trans_back = {v: k for k, v in translation.items()}>>>''.join(map(trans_back.get, morse.split()))
'HELLOWORLD'

Note that this removed the space, though. To fix this, you could use a different symbol than space to separate the morse code sequences. Or use this slightly more complicated version using re.split to split at a space, only if that space is not followed, or not preceded by another space:

>>> ''.join(map(trans_back.get, re.split("(?<! ) | (?! )", morse)))
'HELLO WORLD'

For deciding which way to translate, i.e. whether the original text is morse or plain-text, you could just check whether either the first, or all of the characters of the string are in the translation dictionary, or whether they are valid morse symbols:

ifall(cin translation forcin msg):# translate to morse
elif all(cin".- "forcin msg):# translate backelse:# don't know what to do

Note: This answer was posted before trailing spaces were added to all the entries in the dict.

Solution 2:

You are going to have to check if it is a Morse message or a 'alpha' message:

# build a reversed dict
translation_from_morse = {v: k for k, v in translation.items()}

user_input = input("Input english or morse code message:\n").upper()

if user_input[0] in".-":
    print(" ".join("".join(translation_from[morse] for morse in part.split(" ")) for part in user_input .split("  ")))
else:
    print(" ".join(translation_to.get(c, c) for c in user_input ))

Solution 3:

Translating from a letter to morse code is quite simple in this case. You simply access the value using the key and concatenate each string value to another string. See below:

user_input = input("Input english to translate to morse code: ")

morse_code_message = ""for i in user_input:
    if i in translation.keys():
         morse_code_message += translation[i]
print(morse_code_message)

However, dictionaries are not intended to be used the other way around. So morse to english will be different. You will have to search the dictionary values. See this post if you absolutely must do it this way. A cheap and easy way around this is to just make two translation tables and just use the same logic as is used for english to morse.

Solution 4:

Build a reverse index of the original dict and then you have two convenient lookups. Now you have the problem that morse is a different length than characters. Assuming that the morse intercharacter gap is written as a space, you can consume the input stream one token at a time by first checking if its alpha (pop 1 char) or morse (pop multiple chars).

Note, do i in translation not translation.keys()

translation = {... your original dict ...}
morse_to_alpha = {v,k for k,v in translation.items()}

user_input = input("Input english or morse code message:\n").upper()

while user_input:
    if user_input[0] in translation:
        print(translation.pop(0))
    elif user_input[0] in'.-':
        try:
             separator = user_input.index(' ')
        except ValueError:
             separator = len(user_input)
        morse = user_input[:separator]
        del user_input[:separator+1]
        print(morse_to_alpha[morse])
    else:
        print("unkown symbol") 

Post a Comment for "Using Dictionary And Printing Out Value When Matched Key And Vise-versa"