How to Create a Dataframe from a Dictionary in Pandas
Answer
Use pd.DataFrame(dict) where dictionary keys become column names and values become column data. For row-oriented data, use pd.DataFrame.from_records() or pass a list of dictionaries.
Why This Happens
Dictionaries are the most common way to create dataframes in Python. You need to know how to structure your data depending on whether you're thinking column-wise (keys are column names) or row-wise (each dict is a row).
Solution
The rule: for column-oriented data use pd.DataFrame(dict) directly, for row-oriented data pass a list of dicts. Missing keys automatically become NaN.
import pandas as pd
# โ
Column-oriented: keys are column names, values are lists
data = {'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35]}
df = pd.DataFrame(data)
# โ
Row-oriented: list of dictionaries (each dict is a row)
data = [
{'name': 'Alice', 'age': 25},
{'name': 'Bob', 'age': 30},
{'name': 'Charlie', 'age': 35}
]
df = pd.DataFrame(data)
# โ
From dict with custom index
data = {'name': ['Alice', 'Bob'], 'age': [25, 30]}
df = pd.DataFrame(data, index=['row1', 'row2'])
# โ
From dict of dicts (outer keys become index)
data = {
'row1': {'name': 'Alice', 'age': 25},
'row2': {'name': 'Bob', 'age': 30}
}
df = pd.DataFrame.from_dict(data, orient='index')
# โ
Specify column order
data = {'age': [25, 30], 'name': ['Alice', 'Bob']}
df = pd.DataFrame(data, columns=['name', 'age'])
# โ
Handle missing keys in row-oriented data
data = [
{'name': 'Alice', 'age': 25},
{'name': 'Bob'} # missing 'age'
]
df = pd.DataFrame(data) # missing values become NaNBetter Workflow
In Zerve, each dataframe creation pattern lives in its own block with independent variables. No namespace pollution where products_df, employees_df, and quarterly_df all exist in the same memory, leading to accidental variable reuse. Want to try multiple dictionary structures? Create parallel blocks, compare outputs side by side on the canvas, with zero risk of one experiment overwriting another.
)
&w=1200&q=75)
&w=1200&q=75)
&w=1200&q=75)