{i: i**2 for i in range(10) if i % 2 == 0}
Built-in Data Structures

Meaning

This dictionary comprehension builds a mapping where each even integer in a given range is paired with its square. It eliminates the need for an explicit loop and intermediate assignments, reducing boilerplate. Use it whenever you need a quick lookup table of pre‑computed values.

Primary Function

Data transformation

Communicative Purpose

Generates a dictionary of even numbers to their squares, avoiding explicit loops and manual insertion.

Pattern

{key: key**2 for key in range(limit) if key % 2 == 0}

Core Structure

{...: ... for ... in ... if ...}

Função primária

Data transformation

Propósito comunicativo

Generates a dictionary of even numbers to their squares, avoiding explicit loops and manual insertion.

Situações de gatilho

Data processing: creating a lookup table of precomputed values; Algorithm implementation: mapping inputs to outputs for fast access; Educational examples: demonstrating concise Python syntax.

Contextos

Python scripts, data‑analysis pipelines, algorithmic code, teaching materials, utility libraries.

Padrão

{key: key**2 for key in range(limit) if key % 2 == 0}

Estrutura central

{...: ... for ... in ... if ...}

Slots de substituição

key: int (even integer), limit: int (exclusive upper bound)

Colocados típicos

  • range()
  • if clause
  • for loop
  • dictionary literal
  • comprehension

Substituições comuns

  • Use a for‑loop with dict.update() for clearer step‑by‑step logic (more verbose)
  • use dict(zip(...)) when keys and values are pre‑computed sequences (less flexible)
  • use a generator expression with dict() for lazy evaluation (may be slower).

Erros comuns

{"cause":"Using square brackets [] instead of curly braces {}","consequence":"Creates a list comprehension, not a dictionary, leading to a TypeError when expecting a dict."} {"cause":"Forgetting the if clause parentheses or using a single equals sign","consequence":"SyntaxError or unintended inclusion of odd numbers."} {"cause":"Using range(limit) without specifying an integer limit","consequence":"NameError or TypeError at runtime."} {"cause":"Attempting to assign to the key inside the comprehension (e.g., key = key**2)","consequence":"SyntaxError because assignment is not allowed in comprehensions."} {"cause":"Assuming the comprehension preserves order in Python <3.7","consequence":"Unexpected ordering of keys in older Python versions."}

Similar / contraste

List comprehension → produces a list, not a dict. Set comprehension → produces a set of unique values. Generator expression → yields items lazily, cannot be indexed directly.

Interferências

Coming from JavaScript: you might try to use object literal syntax with commas inside a loop, which is invalid in Python → use dict comprehension with proper braces.

Família do chunk

  • comprehensions
  • dictionary literals
  • mapping constructions

Nuance

Do not use this pattern when the key space is huge and memory consumption becomes a concern; the comprehension builds the entire dict in memory (O(n) space); for very large limits, consider a lazy mapping or database lookup instead.

Efeito pragmático

Enables fast O(1) lookups of precomputed results, reduces code size, and improves readability, which helps prevent bugs from manual insertion errors.

Dica de memória

Think of a dictionary comprehension as a factory line that instantly assembles a catalog of items as they roll off the production line.

Nota

Dictionary comprehensions were introduced in Python 2.7 and are fully supported in all Python 3 versions.

Upgrade path

Use dictionary comprehension with a function or lambda to compute the value, enabling more complex transformations (e.g., {k: func(k) for k in iterable if cond(k)}).

Frequência: HighFormulaicidade: Semi-fixedTipo de construção: dictionary comprehensionPrioridade de aquisição: Active recallPrioridade de output: BothTag de espaçamento: Immediate

Log in to save chunks.