0
0
Pandasdata~5 mins

Creating DataFrame from dictionary in Pandas

Choose your learning style9 modes available
Introduction

We use a dictionary to quickly make a table of data. This helps us organize and analyze information easily.

You have data stored as key-value pairs and want to see it as a table.
You want to convert survey answers stored in a dictionary into a spreadsheet format.
You collected data from different sources and combined it into a dictionary, now want to analyze it.
You want to create a small dataset for testing or learning purposes.
Syntax
Pandas
import pandas as pd

df = pd.DataFrame(data)

data is a dictionary where keys become column names and values are lists of column data.

All lists in the dictionary should be the same length to avoid errors.

Examples
This creates a DataFrame with two columns: Name and Age.
Pandas
import pandas as pd

data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df)
Here, the DataFrame shows cities and their populations.
Pandas
import pandas as pd

data = {'City': ['NY', 'LA', 'Chicago'], 'Population': [8000000, 4000000, 2700000]}
df = pd.DataFrame(data)
print(df)
Sample Program

This program makes a table of students with their scores and if they passed. It prints the table.

Pandas
import pandas as pd

# Create a dictionary with data
student_data = {
    'Student': ['John', 'Emma', 'Sophia'],
    'Score': [88, 92, 95],
    'Passed': [True, True, True]
}

# Convert dictionary to DataFrame
df = pd.DataFrame(student_data)

# Show the DataFrame
print(df)
OutputSuccess
Important Notes

If lists in the dictionary have different lengths, pandas will raise an error.

You can also use an OrderedDict if you want to keep columns in a specific order.

Summary

Use a dictionary with lists to create a DataFrame easily.

Keys become column names, values become column data.

Make sure all lists have the same length for a valid table.