astral-sh/ruff · warning

Expected tuple or list for dictionary comprehension

Error message

Expected tuple or list for dictionary comprehension

What it means

Part of the C417 fix that converts `dict(map(lambda x: (k, v), it))` into a dict comprehension. For the dict target type the lambda body must be a tuple or list literal of key/value elements; any other body expression cannot be transformed, so the fixer bails.

Source

Thrown at crates/ruff_linter/src/rules/flake8_comprehensions/fixes.rs:778

                rpar: vec![],
            }));
        }
        ObjectType::Set => {
            tree = Expression::SetComp(Box::new(SetComp {
                elt: lambda.body.clone(),
                for_in: compfor,
                lpar: vec![],
                rpar: vec![],
                lbrace: LeftCurlyBrace::default(),
                rbrace: RightCurlyBrace::default(),
            }));
        }
        ObjectType::Dict => {
            let elements = match lambda.body.as_ref() {
                Expression::Tuple(tuple) => &tuple.elements,
                Expression::List(list) => &list.elements,
                _ => {
                    bail!("Expected tuple or list for dictionary comprehension")
                }
            };
            let [key, value] = elements.as_slice() else {
                bail!("Expected container to include two elements");
            };
            let Element::Simple { value: key, .. } = key else {
                bail!("Expected container to use a key as the first element");
            };
            let Element::Simple { value, .. } = value else {
                bail!("Expected container to use a value as the second element");
            };

            tree = Expression::DictComp(Box::new(DictComp {
                for_in: compfor,
                lpar: vec![],
                rpar: vec![],
                key: Box::new(key.clone()),
                value: Box::new(value.clone()),

View on GitHub (pinned to 26f38c119c)

Solutions

  1. Re-run ruff so the fix sees current code.
  2. Rewrite manually: `dict(map(lambda x: (k(x), v(x)), it))` -> `{k(x): v(x) for x in it}`.
  3. Add `# noqa: C417` if the lambda body is intentionally not a literal pair.

Example fix

// before
config = dict(map(lambda kv: (kv[0], kv[1]), pairs))
// after
config = {kv[0]: kv[1] for kv in pairs}
Defensive patterns

Strategy: type-guard

Validate before calling

ok = isinstance(l.body, (ast.Tuple, ast.List))

Type guard

def is_pair_literal(lam):
    return isinstance(lam, ast.Lambda) and isinstance(lam.body, (ast.Tuple, ast.List))

Try / catch

try:
    apply_autofix(diagnostic)
except Exception:
    write_dict_comp_manually()

Prevention

When it happens

Trigger: `ruff check --fix` on `dict(map(lambda x: f(x), items))` or `dict(map(lambda x: (x[0], x[1], x[2]), items))` where the lambda body is a call, name, or a longer tuple.

Common situations: Lambdas returning computed pairs via function calls; star-unpacking bodies like `lambda x: (*a, *b)`; stale diagnostics after edits.

Related errors


AI-assisted analysis of astral-sh/ruff@26f38c119c (2026-09-05). Data as JSON: /api/errors/becffe90e4777a3a. Report an issue: GitHub.