lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
nums = "0123456789"
punc = ",.!?;"
space = " "
cs = space+lower
# Dict that converts characters to numbers
chr_to_num = {}
counter = 0
for character in cs:
chr_to_num[character] = counter
counter += 1
enc_msg = "pmogirmkkgrydle jtuwyly"
def split(enc_msg):
return list(enc_msg)
enc_msg = "pmogirmkkgrydle jtuwyly"
print(chr_to_num[tuple(split(enc_msg))])
My goal for the code is to return a list of numbers that correspond with each letter in enc_msg as I’m currently getting:
KeyError: (‘p’, ‘m’, ‘o’, ‘g’, ‘i’, ‘r’, ‘m’, ‘k’, ‘k’, ‘g’, ‘r’, ‘y’, ‘d’, ‘l’, ‘e’, ‘ ‘, ‘j’, ‘t’, ‘u’, ‘w’, ‘y’, ‘l’, ‘y’)
Without the tuple, I get TypeError: unhashable type: ‘list’
>Solution :
The Error
You are getting an error because you’re calling a chr_to_num key which is unvalid: tuple(split(enc_msg)).
Just in case, to clearify, dico["..."] returns the value associated to "..." in the dico dictionary.
In fact, you cannot convert all the values of a tuple/list giving the tuple/list itself. You have to convert each tuple/list element individually.
Solution
To make it work, you should iterate the split(enc_msg) list:
converted_list = []
for letter in split(enc_msg):
converted_list.append(chr_to_num[letter])
Another way to code this is:
converted_list = [chr_to_num[letter] for letter in split(enc_msg)]