{"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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/common.py#L412-L448","documentation":"Raised by the to_dict helper when `into` is exactly the defaultdict *class* (collections.defaultdict) rather than an *instance* of it. to_dict needs a default_factory to construct a defaultdict, which only an instance (e.g. defaultdict(list)) carries. Passing the bare class is rejected so users do not silently get default_factory=None.","triggerScenarios":"ser.to_dict(into=defaultdict); ser.to_dict(into=collections.defaultdict).","commonSituations":"Copy-pasting defaultdict without instantiation; assuming the class itself is a valid mapping factory.","solutions":["Pass an initialized defaultdict: ser.to_dict(into=defaultdict(list)).","Pick the factory matching the value shape (list for grouped, int/float for counters).","If you do not need defaults, use plain dict (the default)."],"exampleFix":"// before\nout = df.groupby('k')['v'].apply(list).to_dict(into=defaultdict)\n// after\nfrom collections import defaultdict\nout = df.groupby('k')['v'].apply(list).to_dict(into=defaultdict(list))","handlingStrategy":"validation","validationCode":"from collections import defaultdict\nif into is defaultdict:\n    raise TypeError('pass an instance: defaultdict(list)')\nout = ser.to_dict(into=into)","typeGuard":"def is_defaultdict_instance(x) -> bool:\n    from collections import defaultdict\n    return isinstance(x, defaultdict)","tryCatchPattern":null,"preventionTips":["Always instantiate defaultdict with its factory before passing to to_dict.","Use plain dict when defaults are not needed."],"tags":["type-error","to-dict","defaultdict","mapping","api-misuse"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}