astral-sh/ruff · warning

Expected container to include two elements

Error message

Expected container to include two elements

What it means

Also raised by the C417 `dict(map(lambda ...))` fix: after extracting the lambda body's tuple/list elements, exactly two (key, value) are required to build a `DictComp`. Tuples of any other length make the rewrite impossible and the fixer bails.

Source

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

            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()),
                lbrace: LeftCurlyBrace::default(),
                rbrace: RightCurlyBrace::default(),
                whitespace_before_colon: ParenthesizableWhitespace::default(),
                whitespace_after_colon: ParenthesizableWhitespace::SimpleWhitespace(

View on GitHub (pinned to 26f38c119c)

Solutions

  1. Make the lambda body a two-element tuple/list, or slice out the two fields you actually need.
  2. Rewrite as an explicit dict comprehension by hand and drop C417.
  3. Suppress with `# noqa: C417` while keeping the longer tuple.

Example fix

// before
d = dict(map(lambda x: (x[0], x[1], x[2]), rows))
// after
d = {x[0]: x[1] for x in rows}
Defensive patterns

Strategy: validation

Validate before calling

assert len(lam.body.elts) == 2, 'dict conversion needs exactly key and value'

Type guard

def is_two_element(body):
    return isinstance(body, (ast.Tuple, ast.List)) and len(body.elts) == 2

Try / catch

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

Prevention

When it happens

Trigger: `ruff check --fix` on `dict(map(lambda x: (a, b, c), items))` or `dict(map(lambda x: (a,), items))` — body container has one or three-plus elements.

Common situations: Refactored lambdas that grew extra tuple fields; datacarrying tuples reused for dict conversion; stale diagnostics after edits.

Related errors


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