How to convert a Python Pandas DataFrame to a dictionary?

Sometimes, we want to convert a Python Pandas DataFrame to a dictionary.

In this article, we’ll look at how to convert a Python Pandas DataFrame to a dictionary.

How to convert a Python Pandas DataFrame to a dictionary?

To convert a Python Pandas DataFrame to a dictionary, we call to_dict.

For instance, we write

df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
df.to_dict('dict')

to create the data frame df.

Then we call to_dict with 'dict' to return the dictionary from the df data frame.

Conclusion

To convert a Python Pandas DataFrame to a dictionary, we call to_dict.