Home > database >  Take a string input from the user and convert into the dictionary, such that key will be a character
Take a string input from the user and convert into the dictionary, such that key will be a character

Time:10-09

Take a string input from the user and convert it into the dictionary, such that key will be a character of string while the value will be its ASCII code.

For example: Input: Hello World Output: {'H': 72, 'e': 101, 'l': 108, 'o': 111, ' ': 32, 'W': 87, 'r': 114, 'd': 100}

I only did part of it!!! Code:

n = input("ENTER A SENTENCE OR WORD: ")
n = dict()

CodePudding user response:

This is probably what you need:

a = input(': ')
d = {c:ord(c) for c in a}
print(d)

CodePudding user response:

You can use map(ord, list) and zip then use dict to get what you want like below:

>>> n = input("ENTER A SENTENCE OR WORD: ")
>>> dict(zip(list(n),(map(ord, n))))

ENTER A SENTENCE OR WORD: Hello World
{'H': 72, 'e': 101, 'l': 108, 'o': 111, ' ': 32, 'W': 87, 'r': 114, 'd': 100}


#For more explanation
>>> list('Hello World')
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

>>> list(map(ord,'Hello World'))
[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

>>> list(zip(list('Hello World'), map(ord,'Hello World')))
[('H', 72),
 ('e', 101),
 ('l', 108),
 ('l', 108),
 ('o', 111),
 (' ', 32),
 ('W', 87),
 ('o', 111),
 ('r', 114),
 ('l', 108),
 ('d', 100)]
  • Related