Pandas DataFrame to List of Dictionaries

Cover Image for Pandas DataFrame to List of Dictionaries
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

🐼 Pandas DataFrame to List of Dictionaries: Easy Conversion Guide

Do you have a Pandas DataFrame and want to convert it into a list of dictionaries? 🤔 Look no further! In this guide, we'll show you how to effortlessly transform your DataFrame into a list of dictionaries, providing you with an easier and more versatile data structure for your needs. Let's dive right in! 💪

The DataFrame and Our Objective

Let's start with the DataFrame we'll be working with:

import pandas as pd

df = pd.DataFrame({
    'customer': [1, 2, 3],
    'item1': ['apple', 'water', 'juice'],
    'item2': ['milk', 'orange', 'mango'],
    'item3': ['tomato', 'potato', 'chips']
})

Our objective is to transform this DataFrame into a list of dictionaries, where each dictionary represents a row in the original DataFrame. The resulting list should look as follows:

rows = [
    {
        'customer': 1,
        'item1': 'apple',
        'item2': 'milk',
        'item3': 'tomato'
    },
    {
        'customer': 2,
        'item1': 'water',
        'item2': 'orange',
        'item3': 'potato'
    },
    {
        'customer': 3,
        'item1': 'juice',
        'item2': 'mango',
        'item3': 'chips'
    }
]

Now that we have a clear understanding of our objective, let's explore the easy solutions to achieve this conversion. 👇

Solution 1: Using the to_dict Method

Pandas provides us with a convenient method called to_dict that can convert our DataFrame into a dictionary-like representation. By calling this method with the orient parameter set to 'records', we can obtain the desired list of dictionaries. Here's how it looks:

rows = df.to_dict(orient='records')

That's it! The to_dict method does all the heavy lifting for us, effectively converting each row of the DataFrame into a dictionary and appending it to our list. 🎉

Solution 2: Iterating Through Rows

If you prefer a more explicit approach, you can iterate through the DataFrame's rows and manually construct each dictionary. Here's an example to demonstrate this method:

rows = []
for _, row in df.iterrows():
    dictionary = {}
    for column, value in row.items():
        dictionary[column] = value
    rows.append(dictionary)

In this solution, we iterate through each row using the iterrows method and construct a dictionary for each row by iterating through the row's items. Finally, we append each dictionary to our rows list.

Which Solution should I choose?

Both solutions achieve the same result, so it ultimately depends on your personal preference. If simplicity and conciseness are what you seek, Solution 1 (to_dict) is the way to go. On the other hand, if you prefer a more granular control over the transformation process, Solution 2 (iterating through rows) might be your flavor. 😉

All Done! What's Next?

Now that you know how to convert a Pandas DataFrame into a list of dictionaries, you can take full advantage of this versatile data structure. It can be particularly helpful when dealing with data ingestion, API responses, or data serialization. Experiment, explore, and find innovative ways to make the most out of your data! 🚀

If you found this guide helpful, make sure to share it with your fellow data enthusiasts! 🙌 And if you have any questions or further insights, don't hesitate to leave a comment below. Let's keep this conversation going!

Keep coding! 💻💡


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello