Home > Enterprise >  why does my dictionary get me "None" as value?
why does my dictionary get me "None" as value?

Time:11-10

dic = {'A':'D','N':'Q','B':'E','O':'R','C':'F','P':'S','D':'G','Q':'T','E':'H','R':'U','F':'I','S':'V','G':'J','T':'W',
         'H':'K','U':'X','I':'L','V':'Y','J':'M','W':'Z','K':'N','X':'A','L':'O','Y':'B','M':'P','Z':'C'}

user_input = input("Enter the word: ").upper()
Key=str(user_input)
print (dic.get(Key))

This is my dictionary but the only answer I get is None

I tried to change the end to this but problem stayed :(

user_input = input("Enter the word: ").upper()
print (dic.get(user_input))

does anyone know how to do it?

CodePudding user response:

It looks like you are misunderstanding how a dictionary is working.

If I guess correctly, you would like to get DEFG when you enter ABCD. What you currently do works only for single letters (if you run dic.get('A') you will have 'D', but dic.get('ABC') will output None as 'ABC' is not a key).

I believe what you want is to perform some kind of substitution cipher, which is easily done with str.maketrans and str.translate:

dic = {'A':'D','N':'Q','B':'E','O':'R','C':'F','P':'S','D':'G',
       'Q':'T','E':'H','R':'U','F':'I','S':'V','G':'J','T':'W',
       'H':'K','U':'X','I':'L','V':'Y','J':'M','W':'Z','K':'N',
       'X':'A','L':'O','Y':'B','M':'P','Z':'C'}

# define a translation table
table = str.maketrans(dic)

# get user input and translate
user_input =input("Enter the word: ").upper()
print(user_input.translate(table))

Example:

Enter the word: ABCD
DEFG

CodePudding user response:

You need to loop over the values in the string:

dict_a={'A':'D','N':'Q','B':'E','O':'R','C':'F','P':'S','D':'G','Q':'T','E':'H','R':'U','F':'I','S':'V','G':'J','T':'W',
         'H':'K','U':'X','I':'L','V':'Y','J':'M','W':'Z','K':'N','X':'A','L':'O','Y':'B','M':'P','Z':'C'}
user_input =(input("Enter the word: ")).upper()
key=user_input
print(''.join([dict_a.get(k) for k in key]))

And do not call a dict dict give it a name that does not conflict with the default classes.

  • Related