Skip to content

Commit 3f6fa35

Browse files
jseaboldwesm
authored andcommitted
ENH: Allow to_dict to return lists and Series
1 parent ee5e5f1 commit 3f6fa35

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

pandas/core/frame.py

+20-3
Original file line numberDiff line numberDiff line change
@@ -749,15 +749,32 @@ def from_dict(cls, data, orient='columns', dtype=None):
749749

750750
return DataFrame(data, dtype=dtype)
751751

752-
def to_dict(self):
752+
def to_dict(self, outtype='dict'):
753753
"""
754-
Convert DataFrame to nested dictionary
754+
Convert DataFrame to dictionary.
755+
756+
Parameters
757+
----------
758+
outtype : str {'dict', 'list', 'series'}
759+
Determines the type of the values of the dictionary. The
760+
default `dict` is a nested dictionary {column -> {index -> value}}.
761+
`list` returns {column -> list(values)}. `series` returns
762+
{column -> Series(values)}.
763+
Abbreviations are allowed.
764+
755765
756766
Returns
757767
-------
758768
result : dict like {column -> {index -> value}}
759769
"""
760-
return dict((k, v.to_dict()) for k, v in self.iteritems())
770+
if outtype.lower().startswith('d'):
771+
return dict((k, v.to_dict()) for k, v in self.iteritems())
772+
elif outtype.lower().startswith('l'):
773+
return dict((k, v.tolist()) for k, v in self.iteritems())
774+
elif outtype.lower().startswith('s'):
775+
return dict((k, v) for k,v in self.iteritems())
776+
else: # pragma: no cover
777+
raise ValueError("outtype %s not understood" % outtype)
761778

762779
@classmethod
763780
def from_records(cls, data, index=None, exclude=None, columns=None,

0 commit comments

Comments
 (0)