LearnFrenzy
Sign in Take a free test

List Comprehensions · List Comprehensions Coding Problems · Question 7

Character frequency with a dict comprehension in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Count the letters of a word with a dict comprehension (ignoring case) and print the letters that occur more than once.

Solution
main.py Run
word = "Programming"
w = word.lower()
freq = {ch: w.count(ch) for ch in w}
print(freq)
print([ch for ch, n in freq.items() if n > 1])

Output Verified by running it on Python 3

{'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}
['r', 'g', 'm']

Repeated characters simply rewrite the same key with the same count. count() makes this O(n²), fine for short words; Counter is better for long text.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links