Dict Comprehension to Map Keys to Lengths in Python

Build a dictionary that maps each word to its character count using a dictionary comprehension.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 14 views 0 copies

Python code

5 lines
Python 3.9+
words = ["apple", "banana", "cherry", "date", "elderberry"]

word_lengths = {word: len(word) for word in words}

print(word_lengths)

Output

stdout
{'apple': 5, 'banana': 6, 'cherry': 6, 'date': 4, 'elderberry': 10}

How it works

A dictionary comprehension {key: value for item in iterable} builds a new dict by evaluating the key and value expressions for each item in the iterable. Here, the key is the word itself and the value is len(word), which returns the number of characters. This is a concise, readable alternative to a loop that manually assigns to a dict. The comprehension runs in one pass and is idiomatic for transforming sequences into lookup maps.

Common mistakes

  • Using `len` incorrectly, e.g., `len([word])` instead of `len(word)`
  • Forgetting that keys must be hashable — if you map a list to its length, it fails
  • Confusing dictionary comprehension syntax with set comprehension — braces are used for both, but sets omit the colon

Variations

  1. Use a generator expression with `dict()`: `dict((word, len(word)) for word in words)`
  2. Map to length using `zip`: `dict(zip(words, map(len, words)))`

Real-world use cases

  • Building a fast lookup of word counts for text analysis or NLP preprocessing.
  • Creating a mapping of file names to their sizes for a file system report.
  • Generating a dictionary that maps product names to character lengths for UI truncation logic.

Sponsored

Run this sample

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

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.