Lesson 04
Dict Comprehension — Squares and Word Lengths
Build Python dictionaries in one line: map each number to its square and each word to its length, then loop items or unpack in a single expression.
What you will learn
- Dict syntax:
{key: value for name in iterable} - Mapping each number to its square
- Mapping each word to
len(word) - Looping with
.items() - Building the dict inline in a
forheader
This continues from Set comprehension. Dictionaries: dict data type.
The big idea
A dict comprehension needs a key and a value, separated by a colon, inside curly braces.
d = {int(val): int(val) ** 2 for val in raw.split(",")}Without the colon you get a set, not a dict.
Squares
Classroom:
print("Enter List of Values separated comma:")
d = {int(val): int(val) ** 2 for val in input().split(",")}Playground:
raw_nums = "2,3,4,5"
d = {int(val): int(val) ** 2 for val in raw_nums.split(",")}
print("Dict of Element=", d)
for k, v in d.items():
print(f"\t{k}--->{v}")| Key | Expression | Value |
|---|---|---|
| 2 | 2 ** 2 |
4 |
| 3 | 3 ** 2 |
9 |
| 4 | 4 ** 2 |
16 |
Word lengths
raw_words = "python,ai,lambda"
wordslengths = {word: len(word) for word in raw_words.split(",")}
for w, length in wordslengths.items():
print(f"\t{w}--->{length}")| Word | len(word) |
|---|---|
| python | 6 |
| ai | 2 |
| lambda | 6 |
You can skip the extra variable and iterate the comprehension directly:
for w, length in {word: len(word) for word in raw_words.split(",")}.items():
print(f"\t{w}--->{length}")Both forms appear in the teaching programs. The named variable is easier to debug; the one-liner is compact.
Optional if
Keep only longer words:
raw_words = "python,ai,lambda"
long_words = {w: len(w) for w in raw_words.split(",") if len(w) > 3}
print(long_words)ai is dropped.
Common mistakes
Missing colon — {x for x in nums} is a set of keys with no values.
Unhashable key — keys must be hashable (int, str, tuple of hashables). Do not use a list as a key.
Reusing input() twice in a script — each call waits for a new line. In the playground, keep one string per example.
Interview cheat sheet
| Question | Answer |
|---|---|
| Dict vs set braces? | Dict has key: value |
| Square mapping? | {n: n**2 for n in nums} |
| Word length mapping? | {w: len(w) for w in words} |
| Pair loop? | .items() |
Practice in the playground
- Change squares to cubes (
** 3). - Add
if len(word) > 2to the word dict. - Print
wordslengths.keys()andwordslengths.values().
Next: Tuple and generator.
Loading playground…
Check your understanding
Dict comprehension quiz
Which is a dict comprehension?
1 / 10