Search code examples
pythonlistdictionarytuplesalphabet

How to apply a dict in python to a string as opposed to a single letter


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])

Solution

  • 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)}