Create a dictionary of characters and their ASCII values from a string, excluding non-alphabetic characters


Creates a dictionary named ascii_values to map alphabetical characters in the text variable to their ASCII values. Here's how the code works:

  • text = "Hello123": This line initializes the text variable with the string "Hello123."
  • ascii_values = {char: ord(char) for char in text if char.isalpha()}: This line uses a dictionary comprehension to create the ascii_values dictionary. It iterates through each character (char) in the text string and checks if the character is alphabetical using the char.isalpha() method. If the character is alphabetical, it creates a key-value pair in the dictionary.
    • for char in text: This part of the code iterates through each character in the text string.
    • ascii_values = {char: ord(char) for char in text if char.isalpha()}: For each alphabetical character, it takes the character itself as the key and retrieves its ASCII value using the ord(char) function, creating the value.
    • if char.isalpha(): This condition ensures that only alphabetical characters are included in the dictionary.
  • print(text): This line prints the original text string to the console.
  • print(ascii_values): This line prints the ascii_values dictionary, which contains alphabetical characters as keys and their corresponding ASCII values as values.

Source Code

text = "Hello123"
ascii_values = {char: ord(char) for char in text if char.isalpha()}
print(text)
print(ascii_values)

Output

Hello123
{'H': 72, 'e': 101, 'l': 108, 'o': 111}

Example Programs