Skip to content

BUG: Fix to_dict(orient='index') to apply 'into' to nested mappings#66034

Open
C1-BA-B1-F3 wants to merge 1 commit into
pandas-dev:mainfrom
C1-BA-B1-F3:fix-to-dict-nested-into
Open

BUG: Fix to_dict(orient='index') to apply 'into' to nested mappings#66034
C1-BA-B1-F3 wants to merge 1 commit into
pandas-dev:mainfrom
C1-BA-B1-F3:fix-to-dict-nested-into

Conversation

@C1-BA-B1-F3

Copy link
Copy Markdown

What does this PR do?

Fixes #65778

This PR fixes a bug where DataFrame.to_dict(orient='index', into=MyDict) only applied the into parameter to the outer mapping, leaving nested row mappings as plain dict.

Example

from collections import OrderedDict
import pandas as pd

df = pd.DataFrame({"A": [1, 2], "B": ["x", "y"]})
result = df.to_dict(orient="index", into=OrderedDict)

# Before fix: result[0] is dict
# After fix: result[0] is OrderedDict
assert isinstance(result[0], OrderedDict)  # Now passes

Changes

  • Modified all three return paths in the orient='index' branch to use into_c for nested mappings instead of dict()
  • Added tests for:
    • OrderedDict with basic DataFrame
    • defaultdict with basic DataFrame
    • Mixed dtypes (object and non-object columns)
    • All object dtype columns

Testing

Added comprehensive tests covering:

  1. test_to_dict_index_into_nested - Tests OrderedDict and defaultdict
  2. test_to_dict_index_into_nested_mixed_dtypes - Tests with mixed column types
  3. test_to_dict_index_into_nested_all_object - Tests with all object columns

All new tests pass.

Fixes GH#65778

Previously, DataFrame.to_dict(orient='index', into=MyDict) only applied
the 'into' parameter to the outer mapping, leaving nested row mappings
as plain dict. This fix ensures 'into' is applied consistently to both
outer and nested mappings.

Changes:
- Modified all three return paths in the 'index' orient branch to use
  into_c for nested mappings instead of dict()
- Added tests for OrderedDict, defaultdict, mixed dtypes, and all
  object dtype cases
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: DataFrame.to_dict(orient="index", into=...) does not apply into to nested mappings

1 participant