{"record":{"id":"9f421ad152d183fe","repo":"PaddlePaddle/PaddleOCR","slug":"cannot-set-key-value-for-element-it-needs-to-be","errorCode":null,"errorMessage":"Cannot set key/value for {element}. It needs to be a tuple (key, value).","messagePattern":"Cannot set key/value for (.+?)\\. It needs to be a tuple \\(key, value\\)\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"ppocr/modeling/heads/rec_unimernet_head.py","lineNumber":90,"sourceCode":"                first_field_iterator = True\n            else:\n                try:\n                    iterator = iter(first_field)\n                    first_field_iterator = True\n                except TypeError:\n                    first_field_iterator = False\n\n            if first_field_iterator:\n                for idx, element in enumerate(iterator):\n                    if (\n                        not isinstance(element, (list, tuple))\n                        or not len(element) == 2\n                        or not isinstance(element[0], str)\n                    ):\n                        if idx == 0:\n                            self[class_fields[0].name] = first_field\n                        else:\n                            raise ValueError(\n                                f\"Cannot set key/value for {element}. It needs to be a tuple (key, value).\"\n                            )\n                        break\n                    setattr(self, element[0], element[1])\n                    if element[1] is not None:\n                        self[element[0]] = element[1]\n            elif first_field is not None:\n                self[class_fields[0].name] = first_field\n        else:\n            for field in class_fields:\n                v = getattr(self, field.name)\n                if v is not None:\n                    self[field.name] = v\n\n    def __delitem__(self, *args, **kwargs):\n        raise Exception(\n            f\"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.\"\n        )","sourceCodeStart":72,"sourceCodeEnd":108,"githubUrl":"https://github.com/PaddlePaddle/PaddleOCR/blob/2661c7c0ef5c613e8f93c6e93b2e052399f0f854/ppocr/modeling/heads/rec_unimernet_head.py#L72-L108","documentation":"This head ships an HF-style ModelOutput dataclass. When constructed from an iterator, each element must be a (key: str, value) tuple so it can be setattr'd; the first element may instead match the first declared field, but any other non-tuple element raises this ValueError.","triggerScenarios":"Calling ModelOutput([...]) with a list whose elements are not 2-tuples starting with a string — e.g. ModelOutput([loss, logits]), ModelOutput([('a',1), (2,'x')]), or zip artifacts where keys were dropped.","commonSituations":"Refactoring output construction in a custom head/loss and passing raw tensors in a list; porting HF utility code that assumed dict(zip(keys, values)); constructing from another model's outputs tuple directly.","solutions":["Pass keyword arguments (ModelOutput(loss=loss, logits=logits)) — the safest form","If using an iterator, ensure every element is a (str_key, value) tuple: ModelOutput(zip(keys, values)) with keys all strings","Convert foreign outputs via its dict(): ModelOutput(**other_output.to_dict()) or iterate items()"],"exampleFix":"# before\nout = ModelOutput([loss, logits])\n# after\nout = ModelOutput(loss=loss, logits=logits)","handlingStrategy":"type-guard","validationCode":"def valid_output_init(items):\n    for el in items:\n        if not (isinstance(el, (list, tuple)) and len(el) == 2 and isinstance(el[0], str)):\n            raise ValueError(f'ModelOutput iterator items must be (str, value) tuples, got {el!r}')\n    return items\n# ModelOutput(valid_output_init(list(zip(keys, values))))","typeGuard":"def is_kv_tuple(el) -> bool:\n    return isinstance(el, (list, tuple)) and len(el) == 2 and isinstance(el[0], str)","tryCatchPattern":"try:\n    out = ModelOutput(items)\nexcept ValueError as e:\n    if 'Cannot set key/value' in str(e):\n        out = ModelOutput(**dict(zip(keys, values)))\n    else:\n        raise","preventionTips":["Prefer keyword construction ModelOutput(loss=..., logits=...)","Always zip string keys with values before passing an iterator","Convert foreign outputs via output.items() or to_dict(), never raw lists"],"tags":["model-output","dataclass","unimernet","api-misuse"],"backgroundTag":null,"analyzedSha":"2661c7c0ef5c613e8f93c6e93b2e052399f0f854","analyzedAt":"2026-08-14T20:17:30.180Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}