#---------------------------------------------------------------------- # Introduction to Dictionaries # # Copyright (C) November 1, 2017 -- Dr. William T. Verts #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Using lists, we can represent Morse codes as a list containing a # whole bunch of two-element lists: [letter,code] where letter is a # one-character string, and code is the equivalent Morse code string # of dots and dashes. To map a letter onto a code, we need a function # to search the list. #---------------------------------------------------------------------- Morse = [["A",".-"], ["H","...."], ["I",".."], ["O", "---"], ["T","-"], ["V","...-"]] def CharToMorse(C): for L in Morse: if (L[0] == C): return L[1] return "" print CharToMorse("A") print CharToMorse("V") #---------------------------------------------------------------------- # With dictionaries, we create a bunch of key:value pairs, but then # we ask for a mapping of letter to code directly without a search # function. #---------------------------------------------------------------------- DMorse = {"A":".-", "H":"....", "I":"..", "O":"---", "T":"-", "V":"...-"} print DMorse["A"] print DMorse["V"]