astral-sh/ruff · error

Expected container to use a value as the second element

Error message

Expected container to use a value as the second element

What it means

An anyhow bail! in fix_unnecessary_map (C40-style comprehension fixes): while rewriting a dict comprehension into a dict literal, the lambda's body container did not contain exactly a key and a value element. The fixer cannot build a valid dict literal from that shape and aborts the fix.

Source

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

                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(
                    SimpleWhitespace(" "),
                ),
            }));
        }
    }

View on GitHub (pinned to 26f38c119c)

Solutions

  1. Skip the autofix when the container does not hold exactly two elements
  2. Extend the fixer to normalize containers with unexpected shapes before rewriting
Defensive patterns

Strategy: try-catch

When it happens

Trigger: Thrown at crates/ruff_linter/src/rules/flake8_comprehensions/fixes.rs:788 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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