{"record":{"id":"eb1e9978fa7a66e7","repo":"pandas-dev/pandas","slug":"to-dict-only-accepts-initialized-defaultdicts","errorCode":null,"errorMessage":"to_dict() only accepts initialized defaultdicts","messagePattern":"to_dict\\(\\) only accepts initialized defaultdicts","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/common.py","lineNumber":430,"sourceCode":"    Returns\n    -------\n    mapping : a collections.abc.Mapping subclass or other constructor\n        a callable object that can accept an iterator to create\n        the desired Mapping.\n\n    See Also\n    --------\n    DataFrame.to_dict\n    Series.to_dict\n    \"\"\"\n    if not inspect.isclass(into):\n        if isinstance(into, defaultdict):\n            return partial(defaultdict, into.default_factory)\n        into = type(into)\n    if not issubclass(into, abc.Mapping):\n        raise TypeError(f\"unsupported type: {into}\")\n    if into == defaultdict:\n        raise TypeError(\"to_dict() only accepts initialized defaultdicts\")\n    return into\n\n\n@overload\ndef random_state(state: np.random.Generator) -> np.random.Generator: ...\n\n\n@overload\ndef random_state(\n    state: int | np.ndarray | np.random.BitGenerator | np.random.RandomState | None,\n) -> np.random.RandomState: ...\n\n\ndef random_state(\n    state: RandomState | None = None,\n) -> np.random.RandomState | np.random.Generator:\n    \"\"\"\n    Helper function for processing random_state arguments.","sourceCodeStart":412,"sourceCodeEnd":448,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/common.py#L412-L448","documentation":"Raised by standardize_mapping (pandas/core/common.py:430) when the `defaultdict` class itself (uninitialized) is passed as `into` to to_dict. defaultdict needs a default_factory to be useful; passing the bare class leaves the factory undefined, so pandas requires an initialized instance like defaultdict(list).","triggerScenarios":"`df.to_dict(into=collections.defaultdict)` (the class, no factory) vs the correct `df.to_dict(into=collections.defaultdict(list))`. Also `into=defaultdict` imported bare.","commonSituations":"Forgetting that defaultdict requires a factory argument; copy-pasting `defaultdict` as a type rather than constructing an instance.","solutions":["Pass an initialized defaultdict: `into=collections.defaultdict(list)` (or dict, set, etc. as factory).","If you don't need defaulting behavior, use `into=dict`.","If you only know the factory at runtime, construct dynamically: `into=collections.defaultdict(factory)`."],"exampleFix":"# before\nfrom collections import defaultdict\ndf.to_dict(into=defaultdict)\n\n# after\nfrom collections import defaultdict\ndf.to_dict(into=defaultdict(list))","handlingStrategy":"validation","validationCode":"from collections import defaultdict\n\ndef validate_defaultdict(into):\n    if into is defaultdict:\n        raise TypeError('Pass an initialized defaultdict, e.g. defaultdict(list)')\n    return into","typeGuard":"from collections import defaultdict\n\ndef is_initialized_defaultdict(obj) -> bool:\n    return isinstance(obj, defaultdict) and obj.default_factory is not None","tryCatchPattern":"try:\n    result = df.to_dict(into=into)\nexcept TypeError as e:\n    if 'initialized defaultdicts' in str(e):\n        from collections import defaultdict\n        result = df.to_dict(into=defaultdict(list))\n    else:\n        raise","preventionTips":["Always construct an instance: defaultdict(list), not the bare class.","Use into=dict when defaulting behavior is not needed.","Document the factory choice near the call site."],"tags":["to-dict","defaultdict","mapping","into","typeerror"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}