Logo

How can I convert a list of dictionaries into a pandas DataFrame?

If you have data stored as a list of dictionaries, you can convert it directly into a Pandas DataFrame simply by passing it to the DataFrame constructor:

import pandas as pd ## Sample list of dictionaries data = [ {"name": "Alice", "age": 25, "city": "New York"}, {"name": "Bob", "age": 30, "city": "Chicago"}, {"name": "Charlie", "age": 35, "city": "San Francisco"} ] ## Create a DataFrame df = pd.DataFrame(data) print(df)
  1. Each dictionary in the list corresponds to one row in the resulting DataFrame.
  2. Dictionary keys become the column names.

If some dictionaries have missing keys compared to others, Pandas will automatically fill in missing values with NaN. For example:

data = [ {"name": "Alice", "age": 25}, {"name": "Bob", "city": "Chicago"} # Missing 'age' ] df = pd.DataFrame(data) print(df)

The missing columns will be filled with NaN in the affected rows.

Note: This is often the most straightforward approach for quickly transforming JSON-like data structures into a workable tabular form in Pandas.

Learn More About Pandas & Python

If you’re looking to deepen your data manipulation skills and Python proficiency, here are some recommended courses from DesignGurus.io:

  1. Grokking Python Fundamentals
    Dive into Python essentials.

  2. Grokking the Coding Interview: Patterns for Coding Questions
    Ideal if you’re preparing for technical interviews, focusing on pattern-based solutions to common coding challenges.

CONTRIBUTOR
TechGrind