-1

I have made my own Morse Code translator where you can enter the code and the corresponding letter prints out. However, what I want to do is that whenever I enter a letter, the code prints out. Here's my code:

MorseCode = {'.-':'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',
            '.----':1,
            '..---':2,
            '...--':3,
            '....-':4,
            '.....':5,
            '-....':6,
            '--...':7,
            '---..':8,
            '----.':9,
            '-----':0
}

print "Type 'help' for the morse code."
print "Type 'end' to exit the program.\n"
while True:
    code = raw_input("Enter code:")
    if code in MorseCode:
        print MorseCode[code]

So the question is: Is there a way to somehow invert this dictionary so whenever I enter 'A', '.-' will print out? I'm only studying python for two weeks now so I'm still mastering the basics before I move on to the more advanced levels. Thank you!

NewComer
  • 31
  • 3

1 Answers1

1

You can use dictionary comprehension (assuming you are using Python 2.6+) to easily create a new, inverted dictionary:

letters_to_morse = {char: code for code, char in MorseCode.items()}

letters_to_morse['A']
>> '.-'
DeepSpace
  • 78,697
  • 11
  • 109
  • 154