Dict Comprehension to Map Keys to Lengths in Python
Build a dictionary that maps each word to its character count using a dictionary comprehension.
Python code
5 lineswords = ["apple", "banana", "cherry", "date", "elderberry"]
word_lengths = {word: len(word) for word in words}
print(word_lengths)
Output
{'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
- Use a generator expression with `dict()`: `dict((word, len(word)) for word in words)`
- 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
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.