Create a dictionary of characters and their counts, excluding whitespace characters, from a string


The counts the occurrences of non-space characters in the given text and creates a dictionary that maps each character to its count. Here's how the code works:

  • text = "hello world": This line initializes the text variable with the input text.
  • char_counts = {char: text.count(char) for char in set(text) if not char.isspace()}: This line uses a dictionary comprehension to create the char_counts dictionary. Here's what happens:
    • {char: ...}: This part of the code creates key-value pairs in the dictionary. The key is a character char, and the value is the result of the text.count(char) expression, which counts the occurrences of char in the text.
    • for char in set(text): This part iterates over each unique character in the text. The set(text) is used to obtain a set of unique characters, eliminating duplicates.
    • if not char.isspace(): This part checks if the character char is not a whitespace character. It ensures that only non-space characters are counted.
  • print(text): This line prints the original text to the console.
  • print(char_counts): This line prints the char_counts dictionary, which contains non-space characters as keys and their counts as values.

Source Code

text = "hello world"
char_counts = {char: text.count(char) for char in set(text) if not char.isspace()}
print(text)
print(char_counts)

Output

hello world
{'e': 1, 'l': 3, 'w': 1, 'r': 1, 'h': 1, 'd': 1, 'o': 2}

Example Programs