Python pandas: How to Convert a Dictionary to a Pandas Series
A pandas Series is a one-dimensional labeled array that can hold any data type - integers, floats, strings, or Python objects. Since Python dictionaries also store data as key-value pairs, converting between these two structures is a natural and frequent operation in data analysis.
In this guide, you'll learn how to convert a dictionary to a pandas Series using pd.Series(), control the index order, handle mismatched keys, and apply this conversion in practical scenarios.
Basic Conversion with pd.Series()
The simplest way to convert a dictionary to a Series is to pass it directly to pd.Series(). The dictionary keys become the Series index, and the values become the data.
import pandas as pd
data = {'a': 100, 'b': 200, 'c': 300, 'd': 400, 'e': 500}
series = pd.Series(data)
print(series)
Output:
a 100
b 200
c 300
d 400
e 500
dtype: int64
The resulting Series preserves the insertion order of the dictionary keys (guaranteed in Python 3.7+).
Specifying a Custom Index Order
You can control the order of the Series by passing an index parameter. The Series will be reordered to match the index you specify:
import pandas as pd
data = {'a': 10, 'b': 20, 'c': 40, 'd': 80, 'e': 160}
series = pd.Series(data, index=['e', 'b', 'd', 'a', 'c'])
print(series)
Output:
e 160
b 20
d 80
a 10
c 40
dtype: int64
The values are rearranged to match the order specified in the index list, not the original dictionary order.
Handling Mismatched Index and Keys
When the index list contains keys that don't exist in the dictionary, pandas assigns NaN to those positions. Conversely, dictionary keys that aren't in the index list are excluded from the Series.
import pandas as pd
data = {'a': 10, 'b': 20, 'c': 40, 'd': 80}
# 'e' is in the index but not in the dictionary
series = pd.Series(data, index=['b', 'd', 'e', 'a', 'c'])
print(series)
Output:
b 20.0
d 80.0
e NaN
a 10.0
c 40.0
dtype: float64
Notice two important changes:
- The key
'e'doesn't exist in the dictionary, so its value isNaN. - The dtype changed from
int64tofloat64becauseNaNis a float value in pandas. Integer columns are automatically promoted to float when they contain missing values.
Converting Different Value Types
Dictionaries with various value types are handled naturally by pandas:
String Values
import pandas as pd
capitals = {'France': 'Paris', 'Germany': 'Berlin', 'Japan': 'Tokyo', 'India': 'New Delhi'}
series = pd.Series(capitals)
print(series)
Output:
France Paris
Germany Berlin
Japan Tokyo
India New Delhi
dtype: object
Float Values
import pandas as pd
prices = {'apple': 1.50, 'banana': 0.75, 'cherry': 3.25, 'date': 5.00}
series = pd.Series(prices)
print(series)
print(f"\nDtype: {series.dtype}")
Output:
apple 1.50
banana 0.75
cherry 3.25
date 5.00
dtype: float64
Dtype: float64
Specifying the Data Type
You can force a specific data type using the dtype parameter:
import pandas as pd
data = {'x': 1, 'y': 2, 'z': 3}
series_float = pd.Series(data, dtype=float)
print(series_float)
Output:
x 1.0
y 2.0
z 3.0
dtype: float64
Naming the Series
You can assign a name to the Series and its index during creation, which is useful when the Series will later become part of a DataFrame:
import pandas as pd
scores = {'Alice': 92, 'Bob': 85, 'Charlie': 78, 'Diana': 95}
series = pd.Series(scores, name='exam_score')
series.index.name = 'student'
print(series)
Output:
student
Alice 92
Bob 85
Charlie 78
Diana 95
Name: exam_score, dtype: int64
Converting a Nested Dictionary
If your dictionary has nested values, each value becomes a single element in the Series (stored as an object):
import pandas as pd
data = {
'user_1': {'name': 'Alice', 'age': 30},
'user_2': {'name': 'Bob', 'age': 25}
}
series = pd.Series(data)
print(series)
print(f"\nType of first element: {type(series['user_1'])}")
Output:
user_1 {'name': 'Alice', 'age': 30}
user_2 {'name': 'Bob', 'age': 25}
dtype: object
Type of first element: <class 'dict'>
If you want to convert a nested dictionary into a structured table, use pd.DataFrame() instead:
import pandas as pd
data = {
'user_1': {'name': 'Alice', 'age': 30},
'user_2': {'name': 'Bob', 'age': 25}
}
df = pd.DataFrame(data).T # Transpose to get users as rows
print(df)
Output:
name age
user_1 Alice 30
user_2 Bob 25
Practical Example: Converting and Analyzing Data
Here's a real-world example of converting a dictionary to a Series and performing analysis:
import pandas as pd
# Monthly sales data
monthly_sales = {
'January': 15000,
'February': 18000,
'March': 22000,
'April': 19500,
'May': 25000,
'June': 21000
}
sales = pd.Series(monthly_sales, name='revenue')
print("Monthly Sales:")
print(sales)
print(f"\nTotal revenue: ${sales.sum():,}")
print(f"Average revenue: ${sales.mean():,.0f}")
print(f"Best month: {sales.idxmax()} (${sales.max():,})")
print(f"Worst month: {sales.idxmin()} (${sales.min():,})")
print(f"\nAbove average months:")
print(sales[sales > sales.mean()])
Output:
Monthly Sales:
January 15000
February 18000
March 22000
April 19500
May 25000
June 21000
Name: revenue, dtype: int64
Total revenue: $120,500
Average revenue: $20,083
Best month: May ($25,000)
Worst month: January ($15,000)
Above average months:
March 22000
May 25000
June 21000
Name: revenue, dtype: int64
Converting Back: Series to Dictionary
To convert a Series back to a dictionary, use the to_dict() method:
import pandas as pd
series = pd.Series({'a': 1, 'b': 2, 'c': 3})
back_to_dict = series.to_dict()
print(back_to_dict)
print(type(back_to_dict))
Output:
{'a': 1, 'b': 2, 'c': 3}
<class 'dict'>
Summary of Key Parameters
| Parameter | Description | Example |
|---|---|---|
data | The dictionary to convert | pd.Series({'a': 1}) |
index | Custom index order; missing keys get NaN | pd.Series(d, index=['b', 'a']) |
dtype | Force a specific data type | pd.Series(d, dtype=float) |
name | Assign a name to the Series | pd.Series(d, name='scores') |
Conclusion
Converting a dictionary to a pandas Series is straightforward with pd.Series():
- Pass the dictionary directly to create a Series where dictionary keys become the index and values become the data.
- Use the
indexparameter to control the order or select a subset of keys. - Missing keys in the index produce
NaNvalues, and the dtype is automatically promoted tofloat64to accommodate them. - Use
dtypeto explicitly set the data type of the resulting Series.
This conversion is one of the most fundamental operations in pandas and serves as a building block for constructing DataFrames, performing analysis, and transforming data between different formats.