Python Dictionary Comprehensions

In the last lesson you learned about Nested Dictionaries and how to hold a dictionary inside another one. Now we will look at a faster way to build dictionaries in the first place. A lot of the time you start with some data and you want to turn it into a dict. The slow way works fine. But there is a one-line way that reads much cleaner once you know it.

πŸ€” Why Dictionary Comprehensions?

Say you have a list of numbers. You want a dict that maps each number to its square. The normal way is to make an empty dict and fill it in a loop.

Here is that loop. It builds the squares dict one key at a time.

numbers = [1, 2, 3, 4]
squares = {}
for n in numbers:
squares[n] = n * n
print(squares)

Output

{1: 1, 2: 4, 3: 9, 4: 16}

That is four lines just to fill one dict. It works. But there is a lot of setup. A dictionary comprehension does the same thing in a single line. A dictionary comprehension is a short way to build a new dict from a sequence, all inside curly braces.

🧩 The Shape

A dictionary comprehension looks a lot like the loop. It is just folded into one line inside { }. You write the key and value first. Then you write the loop part.

This is the general shape. Read it as β€œmake this key and this value, for each item in the sequence”.

# {key: value for item in sequence}

So the part before for says what each key and value should be. The part after for is the loop that feeds it. The colon between key and value is the same colon you already use in a normal dict.

Here is the squares example again, now as a comprehension. It does exactly what the loop did.

numbers = [1, 2, 3, 4]
squares = {n: n * n for n in numbers}
print(squares)

Output

{1: 1, 2: 4, 3: 9, 4: 16}

Same result, one line. The n is the key. The n * n is the value. The for n in numbers walks through the list. That is the whole idea.

If you have already met list comprehensions, this will feel familiar. A list comprehension uses square brackets and gives you one value per item. A dict comprehension uses curly braces and gives you a key and a value per item. The only real difference is that key: value part in the middle.

Tip

A quick way to tell them apart: square brackets [ ] build a list. Curly braces with a colon {key: value ...} build a dict. The colon is the giveaway that you are making a dictionary.

πŸ›’ A More Real Example

Let me show a case that comes up all the time. You have two lists, names and scores, and you want to pair them into a dict. The zip() function walks both lists together. It gives you one name and one score at a time.

This builds a dict that maps each name to their score.

names = ["Alex", "Riya", "Arjun"]
scores = [85, 92, 78]
result = {name: score for name, score in zip(names, scores)}
print(result)

Output

{'Alex': 85, 'Riya': 92, 'Arjun': 78}

Here zip(names, scores) hands back pairs like ("Alex", 85). We unpack each pair into name and score. Then name: score becomes one entry in the dict. So three names and three scores turn into a clean lookup table in one line.

πŸ” Adding a Condition

Now the really useful part. You can add an if at the end to keep only the items you want. This is called filtering. It is where comprehensions really earn their place.

Imagine a price list and you only want the cheap items, say anything under 50. You add if price < 50 after the loop.

Here is a dict of products and prices, filtered down to the affordable ones.

prices = {
"pen": 10,
"bag": 80,
"cup": 25,
"lamp": 120,
"book": 40,
}
cheap = {item: price for item, price in prices.items() if price < 50}
print(cheap)

Output

{'pen': 10, 'cup': 25, 'book': 40}

Read it left to right. For each item and price in prices.items(), keep the entry, but only if price < 50. The bag at 80 and the lamp at 120 get skipped because they fail the condition. Everything under 50 stays.

Notice we used .items() here. That gives us both the key and the value of the original dict at the same time. That is exactly what we need to rebuild a filtered version.

Note

The if part is a filter, so it decides which items to keep. It is not the same as an if-else that changes the value. Here we only keep or skip. We do not change the price itself.

πŸͺž Loop vs Comprehension

It helps to see the two side by side so you can pick the right one. Both build the same cheap dict.

The for loop way The comprehension way
Make an empty dict, then loop and add keys one by one with an if inside. One line: {item: price for item, price in prices.items() if price < 50}.
More lines, but easy to add extra steps inside the loop. Short and clean, best when the logic is simple.

The comprehension is great when the logic is simple and fits on one line. If you need several steps, many conditions, or a lot of inside work for each item, the plain loop is easier to read. Pick the one that stays clear.

⚠️ Common Mistakes

A few things trip people up early on. Watch out for these.

  • Forgetting the colon between key and value. Without it you are building a set, not a dict.
# ❌ Avoid: no colon, this makes a set of values, not a dict
squares = {n * n for n in [1, 2, 3]}
# βœ… Good: the colon makes it a key and a value
squares = {n: n * n for n in [1, 2, 3]}
  • Looping over a dict directly when you need both key and value. Plain for key in my_dict gives you only keys. Use .items() to get both.
prices = {"pen": 10, "bag": 80}
# ❌ Avoid: this loops over keys only, price is undefined
# cheap = {item: price for item in prices if price < 50}
# βœ… Good: .items() gives you key and value together
cheap = {item: price for item, price in prices.items() if price < 50}
  • Cramming too much logic into one line. If you find yourself stacking several conditions and calculations, the line stops being readable. A normal loop is the better choice then.

βœ… Best Practices

  • Reach for a comprehension when you are building a dict from a sequence and the logic is short.
  • Use .items() when you start from another dict and need both the key and the value.
  • Keep one comprehension to one clear job. If it no longer fits comfortably on a line, switch back to a loop.
  • Name your variables for what they hold, like name and score, not single letters, so the line reads almost like a sentence.

πŸŽ“ What You’ve Learned

βœ… A dictionary comprehension builds a new dict in one line using {key: value for item in sequence}.

βœ… It does the same work as an empty dict plus a for loop, just shorter and cleaner.

βœ… You can add if at the end to filter, keeping only the items you want.

βœ… Use .items() to pull both the key and value from an existing dict.

βœ… The colon between key and value is what makes it a dict and not a set.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What does the comprehension {n: n * n for n in [1, 2, 3]} produce?

    Why: Each number becomes a key and its square becomes the value, giving {1: 1, 2: 4, 3: 9}.

  2. 2

    Which part of a dictionary comprehension tells Python it is a dict and not a set?

    Why: Curly braces alone can make a set, but the colon between key and value marks it as a dictionary.

  3. 3

    You start from an existing dict and need both keys and values in the comprehension. What should you loop over?

    Why: The .items() method gives you both the key and the value of each entry at the same time.

  4. 4

    What does the if at the end of a dictionary comprehension do?

    Why: The if acts as a filter, so only entries that pass the condition end up in the new dict.

πŸš€ What’s Next?

You can now build and filter dictionaries fast. Next we will look at the different ways to walk through a dictionary once you have one, key by key, value by value, or both together.

Iterating Through Dictionaries

Share & Connect