Skip to content

BUG: Fix DataFrame.to_dict(orient='index', into=...) to apply into to nested mappings#66037

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

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

Conversation

@C1-BA-B1-F3

Copy link
Copy Markdown

Description

This PR fixes issue #65778 where DataFrame.to_dict(orient="index", into=...) only applies the into parameter to the outer mapping, not to the nested row mappings.

Changes

Bug Fix

  • Modified pandas/core/methods/to_dict.py to apply the into parameter to nested row mappings when orient='index'
  • Fixed all three code paths:
    1. are_all_object_dtype_cols path (all object dtype columns)
    2. box_native_indices path (mixed dtypes with object columns)
    3. else path (non-object dtypes)

Tests

  • Added test_to_dict_index_into_nested test in pandas/tests/frame/methods/test_to_dict.py
  • Tests verify the fix works for all three code paths
  • Tests verify the fix works with different mapping types (MyDict, OrderedDict, defaultdict)

Example

Before the fix:

import pandas as pd

class MyDict(dict):
    pass

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

type(result)      # <class '__main__.MyDict'>
type(result[0])   # <class 'dict'>  # BUG: should be MyDict

After the fix:

type(result[0])   # <class '__main__.MyDict'>  # FIXED

Testing

All tests pass:

  • pytest pandas/tests/frame/methods/test_to_dict.py::TestDataFrameToDict::test_to_dict_index_into_nested -xvs
  • Manual testing with various mapping types and DataFrame configurations

Closes #65778

… nested mappings

- Fixed DataFrame.to_dict() with orient='index' to apply the 'into' parameter to nested row mappings, not just the outer mapping
- Added test_to_dict_index_into_nested to verify the fix works for all code paths:
  * All object dtype columns (are_all_object_dtype_cols path)
  * Mixed dtypes (box_native_indices path)
  * Non-object dtypes (else path)
  * OrderedDict and defaultdict mappings
- Closes pandas-dev#65778
@C1-BA-B1-F3

Copy link
Copy Markdown
Author

Duplicate of PR #66034 which already addresses issue #65778.

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