nigelp12345 nigelp12345 - 1 year ago 102
Python Question

dictionaries key/value in python

I'm trying to build a application that takes input from the user and encodes it and displays it back to the user.every letter in the user input should be replaced by a different letter in the output. This is used with dictionary's key/value. In my code it will only work with one letter, if anymore letters are entered then one it breaks. any ideas would be greatly appreciated to able to type in a word in the input and it prints out the opposite letters as a word in the output.

def getInput():

userInput = input("Enter String to encode: ")
return userInput

def displayOutput(userInput, encoding ):

matchFound = False
for key in encoding:
if (key == userInput):
print("Encoded message", encoding[key])
matchFound = True

if matchFound == False:
print("***Error*** No Match Found!")

def main():

encoding ={"a": "b", "b": "c", "c": "d", "d": "e", "e": "f", "f": "g", "g": "h", "h": "i", "i": "j", "j": "k", "k": "l", "l": "m", "m": "n", "n": "o", "o": "p", "p": "q", "q": "r", "r": "s", "s": "t", "t": "u", "u": "v", "v": "w", "w": "x", "x": "y", "y": "z", "z": "a", " ": "-"}

userInput = getInput()
displayOutput(userInput, encoding)


Answer Source

If I understand your requirements correctly, the following approach could work for you. Try to encode, if there isn't a value entry, then handle the no existing encoding found situation.

def encode(s, encoding):
        return ''.join(encoding[character] for character in s)
    except KeyError:
        print "Encoding not found."

Sample Output:

>>> encoding = {"a": "b", "b": "c", "c": "d", "d": "e", "e": "f", "f": "g", "g": "h", "h": "i", "i": "j", "j": "k", "k": "l", "l": "m", "m": "n", "n": "o", "o": "p", "p": "q", "q": "r", "r": "s", "s": "t", "t": "u", "u": "v", "v": "w", "w": "x", "x": "y", "y": "z", "z": "a", " ": "-"}
>>> encode("helloworld", encoding)    
>>> encode("HelloWorld", encoding) 
Encoding not found.   
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download