Create a dictionary of characters and their frequency in a string


This Python code takes a string text and creates a dictionary char_frequency where the keys are unique characters in the string, and the values are the frequencies of those characters in the string. Here's how the code works:

  • text = "hello world": This line initializes the string text with the text "hello world."
  • char_frequency = {char: text.count(char) for char in set(text)}: This line uses a dictionary comprehension to create the char_frequency dictionary. It does the following:
    • set(text): This part of the code creates a set of unique characters in the text string. Using a set ensures that each character is included only once, eliminating duplicates.
    • {char: text.count(char) for char in set(text)}: This part of the code iterates through each unique character char in the set of unique characters and assigns a key-value pair to the dictionary. The key is the character itself (char), and the value is the result of text.count(char), which counts the number of occurrences of that character in the text string.
  • print(text): This line prints the original text string to the console.
  • print(char_frequency): This line prints the char_frequency dictionary, which contains unique characters as keys and their frequencies as values.

Source Code

text = "hello world"
char_frequency = {char: text.count(char) for char in set(text)}
print(text)
print(char_frequency)

Output

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

Example Programs