{"record":{"id":"2aca2ad9b17b7eab","repo":"roboflow/supervision","slug":"length-of-list-for-key-key-must-be-n","errorCode":null,"errorMessage":"Length of list for key '{key}' must be {n}","messagePattern":"Length of list for key '(.+?)' must be (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/supervision/validators/__init__.py","lineNumber":195,"sourceCode":"            f\"tracker_id must be a 1D np.ndarray with shape {expected_shape}, but got \"\n            f\"shape {actual_shape}\"\n        )\n\n\n@deprecated(  # type: ignore[untyped-decorator]\n    target=_validate_tracker_id,\n    deprecated_in=\"0.29.0\",\n    remove_in=\"0.32.0\",\n)\ndef validate_tracker_id(tracker_id: Any, n: int) -> None:\n    void(tracker_id, n)\n\n\ndef _validate_data(data: dict[str, Any], n: int) -> None:\n    for key, value in data.items():\n        if isinstance(value, list):\n            if len(value) != n:\n                raise ValueError(f\"Length of list for key '{key}' must be {n}\")\n        elif isinstance(value, np.ndarray):\n            if value.ndim == 1 and value.shape[0] != n:\n                raise ValueError(f\"Shape of np.ndarray for key '{key}' must be ({n},)\")\n            elif value.ndim > 1 and value.shape[0] != n:\n                raise ValueError(\n                    f\"First dimension of np.ndarray for key '{key}' must have size {n}\"\n                )\n        else:\n            raise ValueError(f\"Value for key '{key}' must be a list or np.ndarray\")\n\n\n@deprecated(  # type: ignore[untyped-decorator]\n    target=_validate_data,\n    deprecated_in=\"0.29.0\",\n    remove_in=\"0.32.0\",\n)\ndef validate_data(data: dict[str, Any], n: int) -> None:\n    void(data, n)","sourceCodeStart":177,"sourceCodeEnd":213,"githubUrl":"https://github.com/roboflow/supervision/blob/7f254d9784d4c37e0f03cd89ddee164c8db099c0/src/supervision/validators/__init__.py#L177-L213","documentation":"Raised by supervision.validators._validate_data when a value stored in the Detections.data dict is a Python list whose length differs from n (the number of detections). Every list-valued data entry is per-detection metadata and must align row-for-row with xyxy.","triggerScenarios":"Constructing Detections(xyxy=boxes, data={\"track_name\": [\"a\", \"b\"]}) with 3 boxes; appending per-frame scalars as single-element lists for multi-detection batches.","commonSituations":"Storing class names, tracker labels, or annotator strings per detection; broadcasting a constant accidentally as a 1-element list; filtering detections (via indexing) which rebuilds data but manual dict construction skips the filter.","solutions":["Match the count: repeat constants with [value] * len(detections) or np.full.","Prefer np.ndarray over lists for per-detection data — same alignment rule, better vectorization.","After filtering, rebuild data entries with the same index: data={k: [v[i] for i in keep]}.","Use Detections.__getitem__ (det[idx]) which keeps data aligned automatically."],"exampleFix":"# before\ndets = Detections(\n    xyxy=boxes,                                # 3 rows\n    data={\"source\": [\"cam1\"]},                 # 1 element -> ValueError\n)\n\n# after\ndets = Detections(\n    xyxy=boxes,\n    data={\"source\": np.full(len(boxes), \"cam1\")},\n)","handlingStrategy":"validation","validationCode":"n = len(xyxy)\ndata = {\n    k: (v if isinstance(v, np.ndarray) else np.asarray(v))\n    for k, v in data.items()\n}\nfor k, v in data.items():\n    assert v.shape[0] == n, f\"data['{k}'] has {v.shape[0]} entries, expected {n}\"\ndets = Detections(xyxy=xyxy, data=data)","typeGuard":"def data_lists_aligned(data: dict[str, Any], n: int) -> bool:\n    return all(\n        (not isinstance(v, list)) or len(v) == n for v in data.values()\n    )","tryCatchPattern":null,"preventionTips":["Broadcast constants with np.full(n, value), not single-item lists.","Prefer np.ndarray entries in data for per-detection metadata.","Filter via Detections indexing to keep data aligned automatically."],"tags":["detections","data-dict","validation","alignment"],"backgroundTag":null,"analyzedSha":"7f254d9784d4c37e0f03cd89ddee164c8db099c0","analyzedAt":"2026-08-15T05:13:01.950Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}