skip to content

In pandas, what does DataFrame.to_dict() return by default, and with orient='records', 'list' or 'index'?

level: juniorimportance: should knowfreq 40%

answer

  1. orient decides the nesting
  2. column first unless told otherwise
  3. one dict per row for JSON
  4. where the row labels go
  5. missing values in the output

basics

~10 s

By default to_dict() returns {column: {index label: value}}. orient='records' gives a list with one {column: value} dict per row, 'list' gives {column: [values]}, and 'index' gives {index label: {column: value}}.

solid answer

~40 s

`df.to_dict()` uses `orient="dict"`: a dict keyed by column whose values are dicts keyed by index label. `orient="records"` returns a **list** of row dicts, `[{column: value}, ...]`, the shape most JSON APIs and model-serving payloads expect, and it always drops the index. `orient="list"` returns `{column: [values]}`, also without the index. `orient="index"` returns `{label: {column: value}}` and raises `ValueError` if the index has duplicate labels, while the default orient quietly keeps only the last row for a repeated label. To keep the row labels in records, call `reset_index()` first. Missing values are not cleaned: a float `NaN` stays `nan`, while `pd.NA` from a nullable column becomes `None`.

code

python · 15 lines
python
import numpy as np
import pandas as pd

orders = pd.DataFrame(
    {
        "sku": ["A1", "B2"],
        "price": [9.99, np.nan],
        "qty": pd.array([3, None], dtype="Int64"),
    },
    index=["r1", "r2"],
)
print(orders.to_dict())
print(orders.to_dict(orient="records"))
print(orders.to_dict(orient="list"))
print(orders.to_dict(orient="index"))

go deeper

for a junior

Know the default nesting {column: {label: value}} and that orient='records' is the list of row dicts an API usually wants.

for a middle

Explain where each orient puts the index, why records and list drop it, and that reset_index() is how you keep it.

for a senior

Catch the silent losses: duplicate labels overwriting under the default orient, nan leaking into JSON, and pd.NA turning into None in a payload.

for a principal

There is no lead decision in an orient; at most, a team agrees that service payloads go through to_json or a schema check rather than ad hoc to_dict calls.

## What `to_dict` is for `DataFrame.to_dict()` turns a DataFrame into plain Python containers (dicts and lists) so that it can leave pandas: a JSON request body, a model-serving payload, a template context or a test fixture. The main decision is **`orient`**, which sets how the result nests rows, columns and the **index** (the frame's row labels). ## The orients | `orient` | Shape returned | Index kept? | |---|---|---| | `"dict"` (default) | `{column: {label: value}}` | yes, as inner keys | | `"list"` | `{column: [values]}` | no | | `"series"` | `{column: Series}` | yes, inside each Series | | `"records"` | `[{column: value}, ...]`, one dict per row | no | | `"index"` | `{label: {column: value}}` | yes, as outer keys | | `"split"` | `{"index": [...], "columns": [...], "data": [[...], ...]}` | yes, unless `index=False` | | `"tight"` | like `"split"` plus `"index_names"` and `"column_names"` | yes, unless `index=False` | The return type is a `dict` for every orient except `"records"`, which returns a `list` of dicts. `into=` swaps the mapping class (for example `collections.OrderedDict`); a `defaultdict` must be passed already constructed. ## Where the index goes - **`"records"` and `"list"` drop it.** If the row labels carry meaning (an order id set as the index), call `df.reset_index()` first so the label becomes an ordinary column. - **`index=False`** is accepted only with `"split"` or `"tight"`; with any other orient pandas raises `ValueError: 'index=False' is only valid when 'orient' is 'split' or 'tight'`. - **`"split"`** keeps index, columns and data in separate lists, and `pd.DataFrame(**d)` rebuilds the frame from them. ## Duplicate labels Dicts cannot hold the same key twice, so duplicated labels lose data or fail: 1. With **`orient="index"`**, a repeated row label raises `ValueError: DataFrame index must be unique for orient='index'.` 2. With the **default `"dict"` orient**, a repeated row label is not an error: the inner dict keeps only the **last** value for that label, silently. 3. With **duplicate column labels**, every orient except `"tight"` emits `UserWarning: DataFrame columns are not unique, some columns will be omitted.` ## Values and missing values `to_dict` converts NumPy scalars to Python ones where it can, so a `float64` cell becomes a Python `float` and an `int64` cell an `int`. Datetime cells come out as pandas `Timestamp` objects, not strings. Missing values are **not** normalised: - a `NaN` in a `float64` column stays a float `nan`; - a `pd.NA` in a nullable column such as `Int64` comes out as `None`. This matters for JSON. Python's `json.dumps` writes `None` as `null` but writes `nan` as the bare token `NaN`, which strict JSON parsers reject. When JSON is the goal, `df.to_json(orient="records")` writes `null` for both, or replace the missing values before calling `to_dict`. ## Worked example: a scoring payload A team sends recent orders to a model-serving endpoint that expects a JSON list of objects. The frame has `order_id` as its index, a `price` column with a few `NaN` values and a nullable `qty` column. The steps that keep the payload correct: 1. `payload = orders.reset_index()`, so `order_id` survives as a field instead of vanishing with the index. 2. Decide what a missing price means to the model: drop the rows, fill them, or send `null` on purpose. 3. Serialise with `payload.to_json(orient="records")` when the target is JSON text, which writes `null` for missing values; use `to_dict(orient="records")` only when the receiving code wants Python objects. 4. Check the first record by eye: every expected key present, numbers as numbers, no `NaN` token. The same frame as `orient="list"` would suit a library that takes `{feature_name: [values]}`, and as `orient="index"` a lookup cache keyed by `order_id`, provided the ids are unique. ## Choosing the orient 1. A list of rows for an API or a model-serving call: `"records"`, after `reset_index()` if the labels matter. 2. Column vectors for a library that takes `{name: [values]}`: `"list"`. 3. A lookup table keyed by id: set the id as the index, check it is unique, then `"index"`. 4. A lossless round trip including index and column names: `"tight"`. Building a DataFrame from these shapes in the other direction (`pd.DataFrame(records)`, `DataFrame.from_dict`) is covered with constructing frames.

  • How do you keep an order_id index in to_dict(orient='records') output?
    Call `df.reset_index().to_dict(orient="records")`. `reset_index()` moves the index into an ordinary column named after it, so each row dict carries `order_id`. Passing `index=True` does nothing for records, and `index=False` raises `ValueError`, because only `split` and `tight` accept that argument.
  • Why might json.dumps(df.to_dict('records')) produce output another service rejects?
    A `float64` missing value stays a float `nan`, and Python's `json.dumps` writes it as the bare token `NaN`, which is not valid JSON. Use `df.to_json(orient="records")`, which writes `null`, or replace the missing values before converting.

  • to_dict() returns a list of row dicts by default
  • orient='records' keeps the index as a key in each row
  • Duplicate index labels always raise an error
  • to_dict converts every missing value to None
  • index=False works with every orient