How to Convert a Python Dictionary to and from a pandas DataFrame

This is an example of how to cast a Python dict into a dataframe and vice versa. I picked up the df to dict part from this Python and R tips post and the dict to df part from a Stack Overflow post. The below adaptation begins by converting an “NFL quarterbacks” Python dictionary into a dataframe and then back into a dict.

Sometimes a dictionary is adequate to solve a problem with handy methods like get() and items(). You can also do a ton with a dict comprehension. When more complex tabular data operations are needed, the pandas pd.DataFrame class is well equipped for the job. Dictionaries and dataframes are delightfully interoperable, like Tom Brady and any football team on the planet.

import pprint
import pandas as pd

qbs_dict = {
    "Matthew Stafford":"Los Angeles Rams",
    "Joe Burrow":"Cincinnati Bengals",
    "Tom Brady":"Tampa Bay Buccaneers",
    "Pat Mahomes":"Kansas City Chiefs",
    "Tony Romo":"Dallas Cowboys"
qbs_df = pd.DataFrame(qbs_dict.items(), columns=["name", "team"])
qbs_dict = pd.Series(,
pprint.pprint(qbs_dict, sort_dicts=True)
print(qbs_dict.get("Tom Brady", "Name not found."))

Terminal Output

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   name    5 non-null      object
 1   team    5 non-null      object
dtypes: object(2)
memory usage: 208.0+ bytes

{'Joe Burrow': 'Cincinnati Bengals',
 'Matthew Stafford': 'Los Angeles Rams',
 'Pat Mahomes': 'Kansas City Chiefs',
 'Tom Brady': 'Tampa Bay Buccaneers',
 'Tony Romo': 'Dallas Cowboys'}

Tampa Bay Buccaneers

Did you notice that pprint sorts dicts by default?

Here the printed dict is reordered alphabetically on the QB’s names. Per the pprint docs, you can alter this behavior if desired via a keyword argument new in Python version 3.8:

pprint.pprint(qbs_dict, sort_dicts=False)

pandas Documentation

pandas installation documentation




Python Standard Library Documentation