Pandas DataFrame | to_dict method
Start your free 7-days trial now!
Pandas DataFrame.to_dict(~)
method converts the DataFrame to a Python dictionary or list of dictionaries.
Parameters
1. orient
| string
| optional
The rule by which to perform the conversion.
When orient="dict"
(default):
{ column_1: index_1: value_1 index_2: value_2 column_2: ...}
When orient="list"
:
{ column_1: [value_1, value_2, ...] column_2: [...] ...}
When orient="series"
:
{ column_1: Series(value_1, value_2, ...) column_2: Series(...) ...}
When orient="split"
:
{ "index": [index_1, index_2, ...] "columns": [column_1, column_2, ...] "data": [value_1, value_2, ...]}
When orient="records"
:
[ { column_1: value_1 column_2: value_2 ... },{ column_1: value_6 ... }, ...]
When orient="index"
:
{ index_1: { column_1: value column_2: value ... }, index_2: { column_6 ... }, ...}
2. into
| class
| optional
The collections.abc.Mapping
subclass or its instance. This is useful when, instead of the standard Python dict, you want to convert to another type of dictionary such as collections.defaultdict
.
Return Value
Depending on the specified orient
and into
, the return type will vary.
Examples
Consider the following DataFrame:
df = pd.DataFrame({"A":[2,3],"B":[4,5]}, index=["a","b"])df
A Ba 2 4b 3 5
Specifying orient
dict
df.to_dict()
{'A': {'a': 2, 'b': 3}, 'B': {'a': 4, 'b': 5}}
list
df.to_dict(orient="list")
{'A': [2, 3], 'B': [4, 5]}
series
df.to_dict(orient="series")
{'A': a 2 b 3 Name: A, dtype: int64, 'B': a 4 b 5 Name: B, dtype: int64}
For your reference, we show the df
here again:
df
A Ba 2 4b 3 5
split
df.to_dict(orient="split")
{'index': ['a', 'b'], 'columns': ['A', 'B'], 'data': [[2, 4], [3, 5]]}
records
df.to_dict(orient="records")
[{'A': 2, 'B': 4}, {'A': 3, 'B': 5}]
index
df.to_dict(orient="index")
{'a': {'A': 2, 'B': 4}, 'b': {'A': 3, 'B': 5}}
Initialising an ordered dictionary
To initialise an ordered dictionary using its class definition:
from collections import OrderedDictdf.to_dict(into=OrderedDict)
OrderedDict([('A', OrderedDict([('a', 2), ('b', 3)])), ('B', OrderedDict([('a', 4), ('b', 5)]))])
Initialising an defaultdict
Unlike ordered dictionaries, the defaultdict
must be initialised before we pass it into to_dict(~)
:
from collections import defaultdictmy_default_dict = defaultdict(list)df.to_dict(into=my_default_dict)
defaultdict(list, {'A': defaultdict(list, {'a': 2, 'b': 3}), 'B': defaultdict(list, {'a': 4, 'b': 5})})