0
0
PandasHow-ToBeginner · 3 min read

Create DataFrame from Dictionary in pandas: Simple Guide

You can create a DataFrame from a dictionary in pandas using pd.DataFrame(). Pass the dictionary where keys become column names and values become column data. This method quickly converts structured data into a tabular format.
📐

Syntax

The basic syntax to create a DataFrame from a dictionary is:

  • pd.DataFrame(data): Creates a DataFrame from data, which is a dictionary.
  • Keys of the dictionary become column names.
  • Values should be lists or arrays of equal length representing column data.
python
import pandas as pd

data = {'Column1': [1, 2, 3], 'Column2': ['a', 'b', 'c']}
df = pd.DataFrame(data)
💻

Example

This example shows how to create a DataFrame from a dictionary with two columns: numbers and letters.

python
import pandas as pd

data = {'Numbers': [10, 20, 30], 'Letters': ['x', 'y', 'z']}
df = pd.DataFrame(data)
print(df)
Output
Numbers Letters 0 10 x 1 20 y 2 30 z
⚠️

Common Pitfalls

Common mistakes when creating DataFrames from dictionaries include:

  • Using values of different lengths, which causes an error.
  • Passing a dictionary with non-iterable values.
  • Confusing keys as row labels instead of column names.

Always ensure all value lists have the same length.

python
import pandas as pd

# Wrong: lists have different lengths
wrong_data = {'A': [1, 2], 'B': [3, 4, 5]}

# This will raise a ValueError
try:
    df_wrong = pd.DataFrame(wrong_data)
except ValueError as e:
    print(f'Error: {e}')

# Right: lists have the same length
right_data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df_right = pd.DataFrame(right_data)
print(df_right)
Output
Error: All arrays must be of the same length A B 0 1 4 1 2 5 2 3 6
📊

Quick Reference

StepDescription
Prepare dictionaryKeys as column names, values as lists of equal length
Call pd.DataFrame()Pass the dictionary as argument
Check DataFrameUse print() or df.head() to view data
Fix errorsEnsure all value lists have the same length

Key Takeaways

Use pd.DataFrame() with a dictionary where keys are columns and values are lists.
All lists in the dictionary must have the same length to avoid errors.
Dictionary keys become DataFrame column names automatically.
Check your DataFrame output with print() to confirm structure.
Common errors come from mismatched list lengths or non-iterable values.