pythonbeginner

DataFrame to Dict Records

Convert DataFrames to lists of dicts for API responses, JSON export, or further processing.

python
import pandas as pd
import json

df = pd.DataFrame({'id':[1,2,3],'name':['Alice','Bob','Carol'],'score':[90.5,85.0,92.3]})

# List of dicts
records = df.to_dict(orient='records')
print(records)

# JSON string
json_str = df.to_json(orient='records', indent=2)
print(json_str)

# Index-keyed dict
id_map = df.set_index('id').to_dict(orient='index')
print(id_map)

Use Cases

  • API serialization
  • JSON export
  • dict conversion

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.