Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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.

Intermediate35 min

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 for header

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.

python
d = {int(val): int(val) ** 2 for val in raw.split(",")}

Without the colon you get a set, not a dict.

Squares

Classroom:

python
print("Enter List of Values separated comma:")
d = {int(val): int(val) ** 2 for val in input().split(",")}

Playground:

python
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}")
Keys 2 3 4 map to squares 4 9 16
Key Expression Value
2 2 ** 2 4
3 3 ** 2 9
4 4 ** 2 16

Word lengths

python
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}")
python ai lambda mapped to lengths 6 2 6
Word len(word)
python 6
ai 2
lambda 6

You can skip the extra variable and iterate the comprehension directly:

python
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:

python
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

  1. Change squares to cubes (** 3).
  2. Add if len(word) > 2 to the word dict.
  3. Print wordslengths.keys() and wordslengths.values().

Next: Tuple and generator.

Loading playground…

Check your understanding

Dict comprehension quiz

Which is a dict comprehension?

1 / 10