Bain
Bain

Reputation: 844

Dictionary Replace Strings to Numbers in python

I want to create a simple cipher in which it uses Phone numbers in place for the letters (input given).

Here is my code below showing what i'm trying to do with just a sample text, but I get an error code of key error: 'L'

def main():

    phoneCipher = {'id' : A, 'val': 2},{'id' : B, 'val': 22},{'id' : C, 'val': 222},{'id' : D, 'val': 3},{'id' : E, 'val': 33},{'id' : F, 'val': 333},{'id' : G, 'val': 4},{'id' : H, 'val': 44},{'id' : I, 'val': 444},{'id' : J, 'val': 5},{'id' : K, 'val': 55},{'id' : L, 'val': 555},{'id' : M, 'val': 6},{'id' : N, 'val': 66},{'id' : O, 'val': 666},{'id' : P, 'val': 7},{'id' : Q, 'val': 77},{'id' : R, 'val': 777},{'id' : S, 'val': 7777},{'id' : T, 'val': 8},{'id' : U, 'val': 88},{'id' : V, 'val': 888},{'id' : W, 'val': 9},{'id' : X, 'val': 99},{'id' : Y, 'val': 999},{'id' : Z, 'val': 9999}                  

    #THIS PART IS NOT WORKING BUT IS PART OF WHAT I WANT TO BE ABLE TO DO   
    originalMessage = input("Please input your message to be hidden: ")
    print(originalMessage)
    oMessageSplit = originalMessage.split()
    print(oMessageSplit) 



    sampleList = ['L', 'O', 'L']

    phoneCipherDict = dict((x['id'], x['val']) for x in phoneCipher)
    listCiphered = [phoneCipherDict[x] for x in sampleList]

    print(listCiphered)


main()

My analysis and Feedback needed: I believe this seems to be something wrong with maybe its not an integer vs an actual string. If there is no possible way to do this, could someone point me in the right direction to what method to use for something like this?

Upvotes: 1

Views: 127

Answers (3)

Kabie
Kabie

Reputation: 10663

You don't need to do originalMessage.split(), which will only split 'LOL' to ['LOL'].

A simple list(originalMessage) is fine. And you don't even need to do that, because for char in 'LOL' is just the same.

Upvotes: 1

ATOzTOA
ATOzTOA

Reputation: 35980

Try this:

phoneCipher = {'id' : 'A', 'val': 2},{'id' : 'B', 'val': 22},{'id' : 'C', 'val': 222},...

The key should be the string 'L', just L will try to use the value of variable L as key.

Update

For creating a list from string, use

sampleList = list(originalMessage)

Upvotes: 1

Hyperboreus
Hyperboreus

Reputation: 32449

Your dictionary should look something like this:

phoneCipher = {'A': 2, 'B': 22, ...}

Upvotes: 0

Related Questions