October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Write a Python Dictionary Comprehension

A dictionary comprehension creates a new mapping from key and value expressions. Learn the syntax, filtering, duplicate-key behavior, and when an explicit loop is clearer.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Python dictionary comprehension builds a new dictionary by evaluating a key and value expression for each item that passes its optional filters. Its basic form is {key_expression: value_expression for item in iterable if condition}. The colon separates the key from the value; the if clause is optional.

What is the syntax for a dictionary comprehension?

Put the key and value expressions before the for clause, inside braces:

As an Amazon Associate I earn from qualifying purchases.

{key_expression: value_expression for item in iterable if condition}

For example, this maps each number from 0 through 4 to its square:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
squares = {n: n * n for n in range(5)}

The result is {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}. Each item that reaches the pair expression contributes one key/value pair to the new dictionary.

The Python Language Reference describes the form as two expressions separated by a colon, followed by the usual for and if clauses. See Python 3.13.16 Language Reference: Expressions.

How do filters and multiple loops work?

An if clause after the iterable filters items: only those for which the condition is true produce a pair.

even_squares = {n: n * n for n in range(10) if n % 2 == 0}

Dictionary comprehensions can also contain additional for and if clauses. Read them as nested loops and filters, in order: the key and value expressions are evaluated for each path that makes it through all the clauses.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
coordinates = {(x, y): x + y for x in range(2) for y in range(3)}

Here, each value of x is paired with each value of y, so the comprehension produces six entries. Parenthesized tuples are hashable when their elements are hashable, making them valid keys in this example.

How do you transform existing data?

Use expressions that select the key and value you need from each input item. For instance, to map people by identifier:

names_by_id = {person.id: person.name for person in people}

This is concise when each input should contribute one straightforward mapping. Check that identifiers are unique if every person’s name must remain in the result: a repeated identifier causes a later name to replace the earlier one.

What happens when keys repeat or are unhashable?

Dictionary keys must be hashable. If the key expression produces an unhashable value, such as a list, insertion fails with a TypeError.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If multiple iterations produce the same key, the dictionary keeps the value from the last one processed. The comprehension does not warn about duplicate keys. When every value must be preserved, group values into lists or use an explicit loop that handles duplicates deliberately.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How does a comprehension relate to a regular loop?

A dictionary comprehension is a compact way to build a dictionary from a mapping and optional filters. An explicit loop can make the same result while giving you room for multi-step transformations, error handling, or grouping.

Use a comprehension when Use an explicit loop when
The mapping is a clear key/value expression with a simple filter. Each item needs several steps or conditional handling.
Each generated key is expected to be unique, or replacing earlier values is intended. Repeated keys must be detected, reported, or grouped without losing values.

A generator expression is different: it yields values lazily as it is iterated, whereas a dictionary comprehension constructs a dictionary immediately.

What should you know about scope and Python versions?

The comprehension’s iteration variables do not leak into the surrounding scope. Its body runs in an implicitly nested scope, although the iterable expression in the leftmost for is evaluated in the enclosing scope.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Python 3.8 and later, the key expression is evaluated before the value expression. Before 3.8, that order was not specified; CPython evaluated the value first. This distinction matters mainly when expressions have side effects, so keep key and value expressions free of side effects where practical. The version change is documented in the language reference and discussed in PEP 572.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.