Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Examples
  3. Word Frequency Counter

Dictionaries · Python example

Word Frequency Counter

Count repeated words with a dictionary and print the results in alphabetical order.

Open the compilerAll examples
intermediatedictionariescountingsorted

Dictionaries map keys to values, which makes them a natural tool for counting. This example builds a frequency table word by word.

example.py
text = "the cat and the dog and the bird"
counts = {}

for word in text.split():
    counts[word] = counts.get(word, 0) + 1

for word in sorted(counts):
    print(f"{word}: {counts[word]}")

How the code works

  • Each word either receives a new key or updates an existing count.
  • The final dictionary has five keys.
  • The loop prints each word and its count.

Key ideas

  • split() divides the sentence into words.
  • counts.get(word, 0) returns 0 when the word is new.
  • sorted(counts) iterates over the keys in alphabetical order.

Try changing it

  • Use collections.Counter for a shorter implementation.
  • Ignore case and punctuation before counting.
  • Print the three most common words.

Related examples

beginner

Count Vowels

Count the vowels in a sentence with a loop and a membership test.

beginner

Set Operations

Compare two skill sets with union, intersection, and difference.

Previous exampleTuple UnpackingNext exampleSet Operations

Expected output

and: 2
bird: 1
cat: 1
dog: 1
the: 3

Output is compared after trimming trailing whitespace on each line. Run the code to see it produced by CPython in your browser.

Practice next

Apply the same idea with automatic tests or browse a guided project.

ExercisesProjects