Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why won't my conversion from str to list and then conversion to int work?

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading