0

I want to write a function called lazy_encrypt. The input dictionary is a mapping of characters: character pairs it should use to "encrypt" the contents of the input file before writing it to the output file.

If the character is a key in the dictionary, then lazy_encrypt should write the value associated with that key to the output file. If it is not a key, it should write the original character.

It seems to work fine with below example, however, I got an KeyError: 'P' for another example. I have used the "if ..." statement to check if the key is in the dictionary, why is this still happening with my code?

The contents of anIutputFile.txt

#Here is a pretty simple message to encrypt

#When it's encrypted, it will look different

the contents of anOutputFile.txt after running will be:

#Horo is a protty simplo mossago ta oncrypt

#Whon it's oncryptod, it will laak difforont

#Write your function here!
def lazy_encrypt(string1, string2, a_dictionary):
    f = open(string2) # open the file
    o = open(string1,'w')
    
    for line in f:        # iterate over the file line by line
        words = line.split()      # word list
        result = []
        save_to_file = ''
        for word in words:
            new_word = ''
            for c in word:
                if c.lower() in a_dictionary:
                    c = a_dictionary[c]
                    #print(c)
                new_word += c
            result.append(new_word)
        save_to_file = ' '.join(result)
        o.write(save_to_file)
        o.write('\n')
    o.close()     
CodingLife
  • 21
  • 1
  • Perhaps use the `dict.get()` function instead. This enables a default value to a declared, if the key is not found. [Refer to this question](https://stackoverflow.com/q/11041405/6340496). Or change to: `a_dictionary[c.lower()]` to match the `if` statement. And, remember to close the `f` fie handle! Better yet, use a `with` context manager. – S3DEV Oct 01 '21 at 12:46
  • In the case of `P`, you actually check if `p` is in the dictionnary, which is True. But upper `P` is not in the dictionnary, resulting in a KeyError. `c = a_dictionary[c.lower()]` will work. However, with this modification, all upper case letters will be lowered. You will need other things if you want to keep upper case. – RobBlanchard Oct 01 '21 at 12:47

0 Answers0