2

I am trying to output the alphabetical values of a user entered string, I have created a dict and this process works, but only with one letter.

  • If I try entering more than one letter, it returns a KeyError: (string I entered)
  • If I try creating a list of the string so it becomes ['e', 'x', 'a', 'm', 'p', 'l', 'e'] and I get a TypeError: unhashable type: 'list'

I cannot use the chr and ord functions (I know how to but they aren't applicable in this situation) and I have tried using the map function once I've turned it to a list but only got strange results.

I've also tried turning the list into a tuple but that produces the same error.

Here is my code:

import string
step = 1
values = dict()
for index, letter in enumerate(string.ascii_lowercase):
    values[letter] = index + 1
keyw=input("Enter your keyword for encryption")
keylist=list(keyw)
print(values[keylist])

Alt version without the list:

import string
step=1
values=dict()
for index, letter in enumerate(string.ascii_lowercase):
    values[letter] = index + 1
keyw=input("Enter your keyword for encryption")
print(values[keyw])
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
jonbon
  • 23
  • 5

3 Answers3

3

You need to loop through all the letters and map each one individually:

mapped = [values[letter] for letter in keyw]
print(mapped)

This uses a list comprehension to build the list of integers:

>>> [values[letter] for letter in 'example']
[5, 24, 1, 13, 16, 12, 5]

The map() function would do the same thing, essentially, but returns an iterator; you need to loop over that object to see the results:

>>> for result in map(values.get, 'example'):
...     print(result)
5
24
1
13
16
12
5

Note that you can build your values dictionary in one line; enumerate() takes a second argument, the start value (which defaults to 0); using a dict comprehension to reverse the value-key tuple would give you:

values = {letter: index for index, letter in enumerate(string.ascii_lowercase, 1)}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

You most certanly can use ord()

inp = input('enter stuff:')
# a list of the ord() value of alphabetic character
# made uppercase and subtracted 64 --> position in the alphabet
alpha_value = [ord(n.upper())-64 for n in inp if n.isalpha()]
print(alpha_value)

Test:

import string
print([ord(n.upper())-64 for n in string.ascii_lowercase if n.isalpha()])

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
yamm
  • 1,523
  • 1
  • 15
  • 25
0

You can write simple for loop to map alphabet to integer. try to this.

print[(item, (values[item]))for item in keylist]
Haresh Shyara
  • 1,826
  • 10
  • 13