{k: v*2 for k, v in {'a':1,'b':2}.items()}
Iteration Patterns

Meaning

This chunk creates a new dictionary where each value from the original dictionary is multiplied by 2. It avoids the need to write an explicit loop to transform dictionary values. Use this when you have a dictionary of numeric values and want to produce a new dictionary with each value scaled by a factor of 2.

Primary Function

Data transformation

Communicative Purpose

Enables rapid creation of a new dictionary with transformed values

Pattern

{key: value * 2 for key, value in source_dict.items()}

Core Structure

{...: ... * 2 for ... in ... .items()}

Função primária

Data transformation

Propósito comunicativo

Enables rapid creation of a new dictionary with transformed values

Situações de gatilho

Data processing: need to double numeric values in a mapping; Configuration handling: adjust scaling factors stored in a dict

Contextos

Data analysis scripts, ETL pipelines, configuration management code

Padrão

{key: value * 2 for key, value in source_dict.items()}

Estrutura central

{...: ... * 2 for ... in ... .items()}

Slots de substituição

key: hashable, value: number, source_dict: dict of original items

Colocados típicos

  • dict.items()
  • for
  • comprehension
  • multiplication

Substituições comuns

  • Using a for‑loop with explicit dict assignment (more verbose)
  • Using dict.update with a generator expression (less readable)

Erros comuns

Omitting .items() and iterating over keys only → results in KeyError when accessing values; Using mutable default dict as source_dict leading to unexpected sharing; Placing the multiplication outside the comprehension → creates a list of values instead of a dict

Similar / contraste

list comprehension (produces a list); set comprehension (produces a set); dict.update with a loop (imperative style)

Interferências

Coming from JavaScript: treating object literals like Python dict comprehensions and forgetting .items() leads to iterating over keys only

Família do chunk

  • list comprehension
  • set comprehension
  • dict merging
  • dict.update

Nuance

Do not use when values are non‑numeric (e.g., strings) as multiplication will fail; Creates a new dict, O(n) time and memory overhead which may be costly for very large mappings; Keys must be hashable, so unhashable types cannot be used

Efeito pragmático

Provides a concise, readable way to transform mappings, reducing boilerplate and potential bugs

Dica de memória

Doubling a dictionary's values is like giving every employee a 100% raise

Nota

Since Python 3.7, dict order preserves insertion order, which can be important when the transformed dict’s order matters

Frequência: HighFormulaicidade: FixedTipo de construção: comprehensionPrioridade de aquisição: Active recallPrioridade de output: BothTag de espaçamento: Immediate

Log in to save chunks.