Skip to content

ENH: Added Index param to to_dict like in to_json #46398 #46784

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ Other enhancements
- :meth:`pd.concat` now raises when ``levels`` is given but ``keys`` is None (:issue:`46653`)
- :meth:`pd.concat` now raises when ``levels`` contains duplicate values (:issue:`46653`)
- Added ``numeric_only`` argument to :meth:`DataFrame.corr`, :meth:`DataFrame.corrwith`, and :meth:`DataFrame.cov` (:issue:`46560`)
- Added ``index`` parameter to :meth:`DataFrame.to_dict` (:issue:`46398`)

.. ---------------------------------------------------------------------------
.. _whatsnew_150.notable_bug_fixes:
Expand Down
89 changes: 64 additions & 25 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1771,7 +1771,7 @@ def to_numpy(

return result

def to_dict(self, orient: str = "dict", into=dict):
def to_dict(self, orient: str = "dict", into=dict, index=True):
"""
Convert the DataFrame to a dictionary.

Expand Down Expand Up @@ -1807,6 +1807,11 @@ def to_dict(self, orient: str = "dict", into=dict):
instance of the mapping type you want. If you want a
collections.defaultdict, you must pass it initialized.

index : bool default True
When set to False, method returns a dict without an index key
(and index_names if using orient='tight'). Can only be False
when orient='split' or 'tight'.

Returns
-------
dict, list or collections.abc.Mapping
Expand Down Expand Up @@ -1909,43 +1914,77 @@ def to_dict(self, orient: str = "dict", into=dict):
elif orient.startswith("i"):
orient = "index"

if not index and orient not in ["split", "tight"]:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure this is desireable. The default config of index should not lead to a ValueError

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey phofl! Thanks for the feedback! I assume you mean the default value for the index parameter - the default value for the index parameter is True, so it wouldn't lead to a ValueError. This check was directly taken from the implementation of the index parameter in 'to_json'. It checks that index is only True if orient is 'split' or 'tight'. A value error would be raised only when index is set to False AND orient is not 'split' or 'tight'.

raise ValueError(
"'index=False' is only valid when 'orient' is 'split' or 'tight"
)

if orient == "dict":
return into_c((k, v.to_dict(into)) for k, v in self.items())

elif orient == "list":
return into_c((k, v.tolist()) for k, v in self.items())

elif orient == "split":
return into_c(
(
("index", self.index.tolist()),
("columns", self.columns.tolist()),
if not index:
return into_c(
(
"data",
[
list(map(maybe_box_native, t))
for t in self.itertuples(index=False, name=None)
],
),
("columns", self.columns.tolist()),
(
"data",
[
list(map(maybe_box_native, t))
for t in self.itertuples(index=False, name=None)
],
),
)
)
else:
return into_c(
(
("index", self.index.tolist()),
("columns", self.columns.tolist()),
(
"data",
[
list(map(maybe_box_native, t))
for t in self.itertuples(index=False, name=None)
],
),
)
)
)

elif orient == "tight":
return into_c(
(
("index", self.index.tolist()),
("columns", self.columns.tolist()),
if not index:
return into_c(
(
("columns", self.columns.tolist()),
(
"data",
[
list(map(maybe_box_native, t))
for t in self.itertuples(index=False, name=None)
],
),
("column_names", list(self.columns.names)),
)
)
else:
return into_c(
(
"data",
[
list(map(maybe_box_native, t))
for t in self.itertuples(index=False, name=None)
],
),
("index_names", list(self.index.names)),
("column_names", list(self.columns.names)),
("index", self.index.tolist()),
("columns", self.columns.tolist()),
(
"data",
[
list(map(maybe_box_native, t))
for t in self.itertuples(index=False, name=None)
],
),
("index_names", list(self.index.names)),
("column_names", list(self.columns.names)),
)
)
)

elif orient == "series":
return into_c((k, v) for k, v in self.items())
Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/frame/methods/test_to_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,3 +344,19 @@ def test_to_dict_orient_tight(self, index, columns):
roundtrip = DataFrame.from_dict(df.to_dict(orient="tight"), orient="tight")

tm.assert_frame_equal(df, roundtrip)

def test_to_dict_index_orient_split(self):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add the gh reference?

df = DataFrame.from_dict({"a": [1, 3, 4], "b": [9, 11, 12]})
result = df.to_dict(orient="split", index=False)
expected = {"columns": ["a", "b"], "data": [[1, 9], [3, 11], [4, 12]]}
assert result == expected

def test_to_dict_index_orient_tight(self):
df = DataFrame.from_dict({"a": [1, 3, 4], "b": [9, 11, 12]})
result = df.to_dict(orient="tight", index=False)
expected = {
"columns": ["a", "b"],
"data": [[1, 9], [3, 11], [4, 12]],
"column_names": [None],
}
assert result == expected