Create a dictionary of lowercase characters from a string


This Python code creates a dictionary named lowercase_chars where the keys are the alphabetical characters from a given text, and the values are the corresponding lowercase versions of those characters. Here's how the code works:

  • text = "Hello World": This line initializes a string variable named text with the text you want to analyze.
  • lowercase_chars = {char: char.lower() for char in text if char.isalpha()}: This line uses a dictionary comprehension to create the lowercase_chars dictionary. It iterates through each character char in the text and checks if the character is an alphabetical character (using char.isalpha()). For each alphabetical character, it assigns a key-value pair to the dictionary. The key is the character itself (char), and the value is the lowercase version of that character (char.lower()).
    • for char in text: This part of the code iterates through each character in the text.
    • if char.isalpha(): It checks if the character is alphabetical.
  • print(text): This line prints the original text to the console.
  • print(lowercase_chars): This line prints the lowercase_chars dictionary, which contains the lowercase versions of alphabetical characters from the original text.

Source Code

text = "Hello World"
lowercase_chars = {char: char.lower() for char in text if char.isalpha()}
print(text)
print(lowercase_chars)

Output

Hello World
{'H': 'h', 'e': 'e', 'l': 'l', 'o': 'o', 'W': 'w', 'r': 'r', 'd': 'd'}

Example Programs