lough_or_cry lough_or_cry - 7 months ago 38
Python Question

Whitespace characters as both a key and a value in a dictionary

I want to decode whole sentences from Morse code to normal alphabet - my script does just that, but it joins all words - it doesn't preserve spaces. In morseCode (the input) three spaces represent the separation between words, while one space represents the separation between letters.

I tried adding three spaces as a key to the dictionary with corresponding value of one space, but it doesn't seem to work.

def decodeMorse(morseCode):
MORSE_CODE[' '] = ' '
return ''.join(MORSE_CODE.get(i) for i in morseCode.split())

I also tried to separate input using regular expressions, but I failed. Is there a way to make it work using dictionaries? Is it even possible to use whitespaces as keys and inputs in dictionaries?


str.split() splits an input string on arbitrary-width whitespace. This means that you only get those sections of the string that are not whitespace (where whitespace includes spaces).

You'd normally split the input twice; once on the string ' ' to get a list of words, then each word on whitespace to get just the letters:

def decodeMorse(morseCode):
    return ' '.join([
        ''.join([MORSE_CODE.get(i) for i in word.split()])
        for word in morseCode.split('   ')])

If you want to use your approach you'd have to use a regular expression to split and include 3-space separators:

re.split(r'([ ]{3}| )', morseCode)

but then you'd have to filter out the single-space letter separators, as re.split() can either include or not include the separator for the whole split operation, not for individual separator markers.