Count Words in Python with Dictionaries and Sets

Text analysis example that counts total words, finds unique words with a set, and tallies character frequencies with a dictionary.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 13 views 0 copies

Python code

30 lines
Python 3.9+
def analyze_text(text: str) -> dict:
    """Count words, find unique words, and show common characters."""
    words = text.lower().split()
    word_count = len(words)
    unique_words = set(words)
    char_counts = {}
    
    for word in words:
        for char in word:
            if char.isalpha():
                char_counts[char] = char_counts.get(char, 0) + 1
    
    top_chars = sorted(char_counts.items(), key=lambda x: x[1], reverse=True)[:3]
    
    return {
        "total_words": word_count,
        "unique_word_count": len(unique_words),
        "unique_words": sorted(unique_words),
        "top_3_characters": top_chars,
        "contains_python": "python" in unique_words
    }

if __name__ == "__main__":
    sample = "Python is fun Python is easy is is"
    result = analyze_text(sample)
    print("Word count:", result["total_words"])
    print("Unique words:", result["unique_word_count"])
    print("Unique word list:", result["unique_words"])
    print("Top 3 characters:", result["top_3_characters"])
    print("Contains 'python':", result["contains_python"])

Output

stdout
Word count: 7
Unique words: 3
Unique word list: ['easy', 'fun', 'is', 'python']
Top 3 characters: [('i', 4), ('s', 5), ('p', 2)]
Contains 'python': True

How it works

text.lower().split() normalizes case and splits on whitespace, producing a list of words. Converting that list to a set (set(words)) automatically deduplicates to give unique words. The nested loop builds a dictionary char_counts using dict.get(char, 0) + 1, a standard counting idiom. Sorting items by frequency with sorted(..., key=lambda x: x[1], reverse=True)[:3] gets the top three characters. The contains_python check uses set membership, which is O(1) on average.

Common mistakes

  • Forgetting to lower() before splitting, so 'Python' and 'python' count as different words.
  • Using a list instead of a set for unique words, which loses the O(1) membership and automatic deduplication.
  • Including non-alphabetic characters in char_counts by not filtering with isalpha().
  • Assuming sorted() on a set gives insertion order; it does not — you must sort explicitly.

Variations

  1. Use collections.Counter for character counts: `Counter(''.join(words))`.
  2. Use a list comprehension with set for case-insensitive uniqueness: `set(text.lower().split())`.

Real-world use cases

  • Analyzing customer feedback logs to identify most common words and sentiment signals.
  • Building a simple search index that counts term frequencies for ranking.
  • Monitoring chat messages for keyword presence (e.g., 'python') to route support tickets.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.