Convert dict to dataFrame python

Convert Dict to DataFrame python : Step By step Implementation

Dictionary or dict is a key value-based python data structure. Converting dict to dataFrame python is possible with from_dict() function of pandas. Using this function we can convert various forms of python dict. In this article, we will address each of them with code.

 

Converting dict to dataFrame python –

See  It seems that converting dict to dataFrame is straight. But as we all know that dictionary can be of difference type. In order to simplify this, We will see them separately. Here we are distributing the problem into different cases.

Case 1: Simple key-value Python dict with column name-

Let’s do it in steps.

Step 1:

Lets create a sample_dict with some data.

sample_dict = {'key1': 1, 'key2':  2, 'key3': 3}

Step 2:

Now create the dict to dataFrame. But here have explicitly defined the column name.

df = pd.DataFrame(list(sample_dict.items()),columns = ['column1','column2']) 
print(df)
dict to dataframe python with explicitly column name
dict to dataframe python with explicitly column name

Case 2: dict with each value as list –

Step 1:

Let’s create a dict with some data. This will be helpful in a complete demonstration.

sample_dict = {'column1': [1,2,3,4], 
               'column2': [5,6,7,8]} 

Step 2:

Let’s convert the dictionary (dict) into the dataFrame. In order to achieve that we need to use the “from_dict” function. Obviously, as you know that from_dict() function is part of the panda’s module. So we need to import it as well.

import pandas as pd
df = pd.DataFrame.from_dict(sample_dict) 

Once we integrate both step’s code and run together. We get the dataFrame as below.

dict to dataframe python example
dict to dataframe python example

 

Case 3: Converting list of dict into pandas dataFrame-

We will do the same, As we have done in the above sections. Firstly will create a dummy list of the dictionary.

Step 1:

Here is the target python dict.

sample_dict = [{'key1': 1, 'key2':  2, 'key3': 3}, 
         {'key1': 4, 'key2':  5, 'key3': 6}, 
         {'key1': 7, 'key2':  8, 'key3': 9}] 

Step 2:

This section will be the same like Case 2.

import pandas as pd
df = pd.DataFrame.from_dict(sample_dict) 
print(df)
list of dict to dataframe python
list of dict to dataframe python

Conclusion –

Well, I hope this article must have helped in converting dictionary into pandas dataframe. We have tried to cover most of the different scenarios of the dictionary. If you want to add some scenarios with us, please comment below.

Thanks

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner