How do I create a dictionary with input symbols as keys and ascii codes as values?

246 Views Asked by At

I'm making a dictionary in which the keys will be one-character symbols separates by a space that the user inputs. I'm assuming that I have call the ord value in a separate line but I'm not sure how to correctly phrase it. Below is the code I have currently:

inp = input()

inp = inp.split(" ")

d = dict.fromkeys(inp, ord(inp))

print(d)
2

There are 2 best solutions below

2
Ben On

A dictionary comprehension would give you what you want:

inp = input()
d = {x: ord(x) for x in inp}
print(d)

This iterates through the string inp and constructs the key/value pairs from the iterator, x, and ord(x).

This doesn't remove spaces, as you seem to possibly be after by inp.split(" "), but I interpreted this as your attempt to split the string by character. Should you want to remove spaces, remove them from the inp object.

3
Sefa_Kurtuldu On

I converted the input with the split function into a list. Then I added the inputs with the ord() function to an empty list with the append function. Then i created a dictionary called d and combined the two lists with using the zip() function. In this way, created a dictionary with the single characters I entered and their ord value.

inp = input()
inp = inp.split(" ")
ordinput = []
for i in inp:
  x = ord(i)
  ordinput.append(x)
d = dict(zip(inp, ordinput))
print(d)