-1

Given the specifics of a dictionary (see sample dictionary below) and based on user input, I need to match the per-letter input and the keys then output the values.

I was able to get the output that I want, except that when input includes a special character, it will not display as output (only letters).

Here is the sample dictionary:

dict1 = {'a':'q', 'b':'w', 'c':'e', 'd':'r', 'e':'t', 'f':'y', 'g':'u' ...}

I tried with the codes below:

sentence = input("Enter a sentence:")

result = ''.join([dict1.get(x, ' ') for x in sentence])
print(result)

If I input: abc, de. f-g The output: qwe rt yu

I would like to have this output instead: qwe, rt. y-q

Is it possible?

~ EDIT: found my mistake in my code (overlooked something). Was able to fix it. Thanks.

  • 3
    `key.get(x, x)` == use the mapping if possible, else use the letter as is. – Patrick Artner Jul 08 '19 at 07:43
  • Possible duplicate of [replace multiple characters in string with value from dictionary python](https://stackoverflow.com/questions/39048559/replace-multiple-characters-in-string-with-value-from-dictionary-python) – Georgy Jul 08 '19 at 08:01

2 Answers2

0

I would suggest to use:

result = ''.join([ dict1[x] if x in dict1 else x for x in sentence])
pygri
  • 647
  • 6
  • 17
0

Try this :

for k in dict1:
    sentence = sentence.replace(k, dict1[k])

Output :

'qwt, rt. y-u'

In python3.8, you can try this list comprehension using walrus operator :

sentence = [sentence:=sentence.replace(k, dict1[k]) for k in dict1][-1]

Output :

'qwt, rt. y-u'
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56