Convert list of dictionaries to pandas DataFrame

Share This Post

In this tutorial, we will learn how to convert a list of dictionaries into a pandas DataFrame. This is a very common task when working with data, and pandas make it easy to do.

We will start by importing the necessary modules, then we will create a list of dictionaries.

Next, we will use the pandas DataFrame constructor to create a DataFrame from our list of dictionaries.

Finally, we will print out the contents of our DataFrame.

Convert list of dictionaries to pandas DataFrame

import pandas as pd
my_list = [{'a': 'foo', 'b': 'bar'}, {'c': 'baz', 'd': 'qux'}]
df = pd.DataFrame(my_list)
print(df)

Output

     a    b    c    d
0  foo  bar  NaN  NaN
1  NaN  NaN  baz  qux

As you can see, our DataFrame contains two rows and four columns. The first row contains the data from the first dictionary in our list, and the second row contains the data from the second dictionary. Each column represents a key from one of the dictionaries, and the values are the corresponding values for those keys.

Now that we know how to convert a list of dictionaries into a pandas DataFrame, let’s see how we can use this to our advantage.

Suppose we have a list of customer data, and we want to create a DataFrame from it.

  • We can do this by creating a dictionary for each customer, with the keys being the customer’s information (name, address, etc.) and the values being the corresponding values for those keys.
  • Then, we can simply pass our list of dictionaries into the DataFrame constructor to create our DataFrame.
customer_list = [{'name': 'John Doe', 'address': '123 Main Street'},
{'name': 'Jane Smith', 'address': '456 Elm Street'}]
customer_df = pd.DataFrame(customer_list)
print(customer_df)

Output

         name          address
0    John Doe  123 Main Street
1  Jane Smith   456 Elm Street

As you can see, this is a very powerful way to create a DataFrame from data that is stored in a list of dictionaries. This can be very helpful when working with data that is stored in JSON format.

Read More: Python Program To Convert Hex String To Decimal

spot_img

Related Posts

Python for Loop Iteration: How to Easily Manipulate a List

One of the most powerful features of the Python...

How To Get First Characters of a String in Python

Way to find the first characters of a string...

How To Convert Tuple To String In Python

In this post, you will learn how to convert...

How To Convert String to Double in Python

Good to hear, that you want to convert a...

Python TypeError: String Index Out Of Range Solution

A string is an array of characters and part...

How To Remove Empty Strings From a List Of Strings

On this page, we will discuss how to remove...
- Advertisement -spot_img