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

Meaning

Creates a new dictionary with keys and values swapped from the given dictionary.

Primary Function

Inverts a dictionary mapping.

Communicative Purpose

Expresses a dictionary comprehension that swaps keys and values.

Pattern

{v:k for k,v in <iterable>.items()}

Core Structure

{v:k for k,v in <iterable>.items()}

Função primária

Inverts a dictionary mapping.

Propósito comunicativo

Expresses a dictionary comprehension that swaps keys and values.

Situações de gatilho

When you need to reverse a mapping, e.g., to look up keys by their values.

Contextos

Data transformation, building lookup tables, inverting mappings.

Padrão

{v:k for k,v in <iterable>.items()}

Estrutura central

{v:k for k,v in <iterable>.items()}

Slots de substituição

<iterable>: any iterable yielding key‑value pairs (e.g., dict.items(), list of tuples, zip(...))

Colocados típicos

  • dict
  • items()
  • dict comprehension
  • zip
  • lookup table

Substituições comuns

  • Any iterable of pairs
  • e.g.
  • list of tuples
  • zip(*pairs)

Erros comuns

Assuming values are unique; duplicate values cause later keys to overwrite earlier ones.

Similar / contraste

Similar to dict(zip(values, keys)) but more readable; contrasts with the identity comprehension {k:v for k,v in d.items()}.

Interferências

If values are not hashable or are duplicated, information may be lost.

Família do chunk

  • dictionary comprehensions

Nuance

Only works when values are hashable and unique; otherwise later keys overwrite earlier ones.

Efeito pragmático

Conveys the idea of inverting a mapping for reverse lookup.

Dica de memória

Think ‘flip the dictionary’.

Nota

Useful for creating reverse lookup dictionaries; beware of non‑unique values.

Upgrade path

Learn basic dict comprehensions, then explore dict constructor with zip and handling duplicate values.

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

Log in to save chunks.