Python Glossary Русский

all Python 3astterm

ast.DictComp

expressions

The node of a dict comprehension {k: v for …}: the key and value expressions in key and value, plus a list of loops in generators.

Syntax

ast.DictComp(key, value, generators)

Every for in the comprehension is a separate item of generators (a comprehension node with target, iter, ifs and is_async), and its if conditions sit in that loop's ifs list. The order of generators matches the order of for clauses in the source, so the first item is the outer loop. A plain {k: v} display is a Dict, not a DictComp.

Examples

import ast
node = ast.parse('{k: v for k, v in items if v}', mode='eval').body
print(node.key.id, node.value.id, len(node.generators))  # → k v 1
gen = node.generators[0]
print(type(gen.target).__name__, gen.iter.id, len(gen.ifs))  # → Tuple items 1

See also

Open in the full glossarydocs.python.orgReport an inaccuracy