This is meant to be a function that decrypts an encrypted text from the dictionary and the should output CAB BA, instead it gives a longer result

Viewed 65

The encryption works quite well to give "JOP PO". But the decryption of this same "JOP PO" in the decryption part gives "CABBA" instead of "CAB BA". and when I include an elif under the decryption loop it gives me some long stuff like "jjjjjcjjooooaooppppbpp pppppbppoooaoo"

en_dict = {'A' : 'O', 'B' : 'P', 'C' : 'J', 'Z' : 'Z', '0' : 9, '1' : 8, '8' : 1, '9' : 0}

unencrypted_item = "cAb ba"
unencrypted_item = unencrypted_item.upper()

def encrypt(unencrypted_data):
    result = ""
    for i in unencrypted_item:
        if i not in en_dict:
            result+=i
        else:    
            result+=en_dict[i]
    return result

print(encrypt(unencrypted_item))

encrypted_item = "jop po"
encrypted_item = encrypted_item.upper()

def decrypt(enc_data):
    result = ""
    for i in encrypted_item:
        for n,o in en_dict.items():
            if i == o:
                result += n
    return result


print(decrypt(encrypted_item))`
1 Answers

I solved the issue by unzipping the dictionary to get the keys and values. Then I reassigned the values as the keys and the keys as the values.

encrypted_item = "jop po"
encrypted_item = encrypted_item.upper()

def decrypt(enc_data):
    [*alpha],[*enc_key] = zip(*en_dict.items())
    dec_dict = dict(zip(enc_key,alpha))
    result = ""
    for i in encrypted_item:
        if i not in dec_dict:
            result += i 
        else:
            result += dec_dict[i] 
    return result

        


print(decrypt(encrypted_item))    ```
Related