How do you convert a Python dictionary into a Pandas DataFrame? | A1Lab@MZeeshanM to PythonEnglish • 4 days ago

How do you convert a Python dictionary into a Pandas DataFrame?

message-square
0

Pass the dictionary directly to pd.DataFrame(data) when keys represent column names mapped to equal-length lists/arrays, or use pd.DataFrame.from_dict(data, orient="index") (or pd.DataFrame([data]) for a single flat scalar dictionary) when keys represent row labels or individual records.

Basic Example

import pandas as pd

# 1. Dict of lists/arrays -> Keys become column names (Default: orient="columns")
col_data = {
    "name": ["Alice", "Bob", "Charlie"],
    "age": [28, 34, 25],
    "city": ["Lahore", "Karachi", "Islamabad"],
}
df_cols = pd.DataFrame(col_data)
print(df_cols)
#       name  age       city
# 0    Alice   28     Lahore
# 1      Bob   34    Karachi
# 2  Charlie   25  Islamabad

# 2. Flat scalar dict -> Wrap in a list [d] to create a single-row DataFrame
single_record = {"name": "Alice", "age": 28, "city": "Lahore"}
df_single = pd.DataFrame([single_record])

# 3. Dict of dicts / row-keyed dict -> Use orient="index" so keys become row index labels
row_data = {
    "u1": {"name": "Alice", "age": 28},
    "u2": {"name": "Bob", "age": 34},
}
df_rows = pd.DataFrame.from_dict(row_data, orient="index")

Key Details & Edge Cases

  • ValueError: If using all scalar values, you must pass an index:
    • Passing a flat dictionary of scalar values directly (pd.DataFrame({"a": 1, "b": 2})) raises this ValueError because Pandas cannot infer how many rows you want. Fix it either by wrapping the dictionary in a list (pd.DataFrame([d])) or by supplying an explicit index (pd.DataFrame(d, index=[0])).
  • ValueError: All arrays must be of the same length:
    • In standard pd.DataFrame(col_data), every list/array value must have identical length. If your dictionary contains uneven-length lists and you want shorter columns padded with NaN, convert values to pd.Series first:
      uneven = {"a": [1, 2, 3], "b": [10, 20]}
      df_padded = pd.DataFrame({k: pd.Series(v) for k, v in uneven.items()})
      
  • Nested dictionaries (pd.json_normalize()):
    • pd.DataFrame.from_dict() only flattens one level of nesting—deeper nested dictionaries remain stored as raw dict objects inside cells. Use pd.json_normalize(nested_dict) (or pd.json_normalize(list_of_nested_dicts)) to flatten nested keys into dot-separated columns (e.g., user.address.city).
  • Simple 2-column key-value table from a flat dictionary (list(d.items())):
    • If you have a flat mapping like {"apples": 5, "bananas": 8} and want a two-column DataFrame with custom column names (item and count), pass list(d.items()):
      counts = {"apples": 5, "bananas": 8}
      df_kv = pd.DataFrame(list(counts.items()), columns=["item", "count"])
      
  • Specifying column subset or explicit row index order: pd.DataFrame.from_dict(col_data, orient="columns") does not accept a columns= filter, whereas pd.DataFrame(col_data, columns=["name", "city"]) selects and orders only the specified columns cleanly.

Comparison of Dictionary-to-DataFrame Conversion Methods

Input Dictionary Structure Method / Syntax Resulting Layout Best Used When
{"col1": [1, 2], "col2": [3, 4]} pd.DataFrame(d) Keys $\rightarrow$ Columns; lists $\rightarrow$ Rows Columnar data with equal-length sequences.
{"col1": 1, "col2": 2} (flat scalars) pd.DataFrame([d]) Single-row DataFrame (index=[0]) Converting a single JSON/dict record into a 1-row DataFrame.
{"row1": {"a": 1}, "row2": {"a": 2}} pd.DataFrame.from_dict(d, orient="index") Outer keys $\rightarrow$ Row index; inner keys $\rightarrow$ Columns Key-indexed records (e.g., user IDs or dates mapped to attribute dicts).
{"k1": "v1", "k2": "v2"} (2-col table) pd.DataFrame(list(d.items()), columns=["k", "v"]) Two columns (k and v), one row per pair Turning a simple lookup dictionary into a 2-column key-value table.
{"user": {"id": 1, "geo": {"lat": 31.5}}} pd.json_normalize(d) Flattened columns (user.id, user.geo.lat) Deeply nested JSON/API response dictionaries.