Create a dictionary of characters and their ASCII values from a string


This Python code takes a string text and creates a dictionary ascii_values where the keys are characters from the string, and the values are their corresponding ASCII values. Here's how the code works:

  • text = "Tutor Joes": This line initializes a string variable text with the value "Tutor Joes."
  • ascii_values = {char: ord(char) for char in text}: This line uses a dictionary comprehension to create the ascii_values dictionary. It iterates through each character char in the text string and assigns a key-value pair to the dictionary. The key is the character itself (char), and the value is the ASCII value of that character, obtained using the ord(char) function.
    • for char in text: This part of the code iterates through each character in the text string.
    • {char: ord(char) for char in text}: It uses a dictionary comprehension to create key-value pairs where the key is the character char, and the value is its corresponding ASCII value.
  • print(text): This line prints the original text string to the console.
  • print(ascii_values): This line prints the ascii_values dictionary, which contains the characters from the original string as keys and their ASCII values as values.

Source Code

text = "Tutor Joes"
ascii_values = {char: ord(char) for char in text}
print(text)
print(ascii_values)

Output

Tutor Joes
{'T': 84, 'u': 117, 't': 116, 'o': 111, 'r': 114, ' ': 32, 'J': 74, 'e': 101, 's': 115}

Example Programs