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


i trying output alphabetical values of user entered string, have created dict , process works, 1 letter.

  • if try entering more 1 letter, returns keyerror: (string entered)
  • if try creating list of string becomes ['e', 'x', 'a', 'm', 'p', 'l', 'e'] , typeerror: unhashable type: 'list'

i cannot use chr , ord functions (i know how aren't applicable in situation) , have tried using map function once i've turned list got strange results.

i've tried turning list tuple produces same error.

here code:

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

alt version without list:

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

you need loop through letters , map each 1 individually:

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

this uses list comprehension build list of integers:

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

the map() function same thing, essentially, returns iterator; need loop on object see results:

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

note can build values dictionary in 1 line; enumerate() takes second argument, start value (which defaults 0); using dict comprehension reverse value-key tuple give you:

values = {letter: index index, letter in enumerate(string.ascii_lowercase, 1)} 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -