Home > Net >  Assign alphabets in Numbers
Assign alphabets in Numbers

Time:04-27

I am trying to assign alphabets in to numbers. When I print 1 I want to get "a". I tried many codes. Please help me to get out of this issue.

characters = 'abcdefghijklmnopqrstuvwxyz'
d = {}
for x in range(len(characters)):
    d[characters[x]] = x 1

CodePudding user response:

Your characters string is most of the way to being a solution all on its own. If you add an extra character to the start of the string (to take up the 0 space), you can just use the number as the index into the string:

>>> characters = ' abcdefghijklmnopqrstuvwxyz'
>>> characters[1]
'a'

CodePudding user response:

You're mixing up the keys and the values in your dictionary. Since you want to look up letters using integer indices, you want to use the index as the key and the letter as the value, not the other way around:

d = {}
for x in range(len(characters)):
    d[x   1] = characters[x]

print(d[1])

This outputs:

a
  • Related