{"record":{"id":"4871677e012a5bc8","repo":"roboflow/supervision","slug":"shape-of-np-ndarray-for-key-key-must-be-n","errorCode":null,"errorMessage":"Shape of np.ndarray for key '{key}' must be ({n},)","messagePattern":"Shape of np\\.ndarray for key '(.+?)' must be \\((.+?),\\)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/supervision/validators/__init__.py","lineNumber":198,"sourceCode":"\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)\n\n\ndef _validate_xy(xy: Any, n: int, m: int) -> None:","sourceCodeStart":180,"sourceCodeEnd":216,"githubUrl":"https://github.com/roboflow/supervision/blob/7f254d9784d4c37e0f03cd89ddee164c8db099c0/src/supervision/validators/__init__.py#L180-L216","documentation":"Raised when building or validating a `Detections` (or similar) object whose `data` dictionary contains a 1-D np.ndarray whose length does not equal the number of detections `n`. Every entry in `data` must be aligned with the `xyxy` array so per-detection metadata stays indexable. The library enforces this so annotators and sinks cannot silently read out-of-range indices.","triggerScenarios":"Calling `sv.Detections(...)` or the (deprecated) `validate_data` with e.g. `data={'tracker_id': np.array([1, 2])}` while `xyxy` has 3 rows; or a `CLASS_NAME_DATA_FIELD` array built from a shorter/longer list than the detections count.","commonSituations":"Filtering detections (`.with_nms()`, slicing, boolean masks) but keeping the old `data` arrays; building `data` from a separate loop that produced a different item count; passing a Python list of names that was converted to ndarray of the wrong length.","solutions":["Rebuild each `data` array from the same source length as `xyxy`, e.g. `data={'class_name': np.array(names[:len(detections.xyxy)])}`.","After any filtering/slicing of detections, re-derive `data` values with the same mask or indices used for `xyxy` instead of reusing stale arrays.","Add an assert before construction: `assert len(values) == len(xyxy)` for every key in `data`."],"exampleFix":"// before\ndetections = sv.Detections(\n    xyxy=boxes,  # (4, 4)\n    data={CLASS_NAME_DATA_FIELD: np.array(['dog', 'cat'])},  # length 2 != 4\n)\n// after\ndetections = sv.Detections(\n    xyxy=boxes,\n    data={CLASS_NAME_DATA_FIELD: np.array(['dog', 'cat', 'dog', 'cat'])},\n)","handlingStrategy":"validation","validationCode":"n = xyxy.shape[0]\nassert all(\n    (not isinstance(v, np.ndarray)) or v.shape[0] == n for v in data.values()\n), 'data arrays misaligned with xyxy'","typeGuard":"def data_aligned(data: dict, n: int) -> bool:\n    return all(\n        v.shape[0] == n if isinstance(v, np.ndarray) else len(v) == n\n        for v in data.values()\n    )","tryCatchPattern":"try:\n    sv.Detections(xyxy=xyxy, data=data)\nexcept ValueError as e:\n    raise RuntimeError(f'misaligned data dict: {e}') from e","preventionTips":["Derive every data array from the same source list length as xyxy.","Apply identical masks/indices to xyxy and data arrays when filtering.","Add a length assert helper in test pipelines."],"tags":["detections","numpy","shape-mismatch","data-dict"],"backgroundTag":null,"analyzedSha":"7f254d9784d4c37e0f03cd89ddee164c8db099c0","analyzedAt":"2026-08-15T05:13:01.950Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}