Skip to main content

Pandas has a builtin method of converting a dictionary whose keys are column labels, and whose values are a list of table entries, into a DataFrame. In other words, Pandas will convert the following dictionary

dictOne = {"Column A":[1, 2, 3],
		   "Column B":[4, 5, 6],
		   "Column C":[7, 8, 9]}

into the following Pandas DataFrame:

import pandas as pd
pd.DataFrame(dictOne)
>    Column A  Column B  Column C
> 0         1         4         7
> 1         2         5         8
> 2         3         6         9

As you can see from the above example, conversion from dictionary to DataFrame was as simple as calling the pandas.DataFrame class constructor on the dictionary. You don’t see a cal to the from_dict method because it’s automatically called when we reference the pandas.DataFrame constructor. If we want to access additional features for importing dictionaries, we’ll need to use the from_dict method directly. Let’s take a look at how we would do that.


from_dict Method

The pandas.DataFrame method from_dict has the format:

pandas.DataFrame.from_dict([data], orient='columns', dtype=None, columns=None)`

where

  1. [data] is the dictionary object we wish to import (or convert)
  2. orient is how each dictionary entry forms the frame. Can be 'index' or 'column', with 'column' as default
    • If each dictionary entry is a row to the DataFrame then use 'index'
    • If each dictionary entry is a column to the DataFrame then use 'column'
  3. dtype is an option to force the given data into a specified type. For example dtype=str will convert all entries into strings, and dtype=float will convert entries into floating point numbers. The default will be to infer the data type based on the input.
  4. columns will take a list of column labels if orient='index' 

We can replicate the above example by directly using the from_dict method like this:

import pandas as pd # Don't forget to import!
dictOne = {"Column A":[1, 2, 3],
		   "Column B":[4, 5, 6],
		   "Column C":[7, 8, 9]}
df = pd.DataFrame.from_dict(dictOne)	
print(df)
>    Column A  Column B  Column C
> 0         1         4         7
> 1         2         5         8
> 2         3         6         9

Now suppose we have a dictionary containing the rows of a DataFrame. We can import this data using the orient='index' option:

import pandas as pd # Don't forget to import!
dictTwo = {"Row 1":[1, 2, 3],
		   "Row 2":[4, 5, 6],
		   "Row 3":[7, 8, 9]}
df = pd.DataFrame.from_dict(dictTwo, orient='index')	
print(df)
>        0  1  2
> Row 1  1  2  3
> Row 2  4  5  6
> Row 3  7  8  9

Now we see that the dictionary labels become the index names, and the list entries become the column values. Notice that because a list of column labels was not specified, Pandas automatically picked a vector of numbers as the column names. We can add a custom set of names ourselves using the columns option.

import pandas as pd # Don't forget to import!
colNames = ["Column A", "Column B", "Column C"]
dictTwo = {"Row 1":[1, 2, 3],
		   "Row 2":[4, 5, 6],
		   "Row 3":[7, 8, 9]}
df = pd.DataFrame.from_dict(dictTwo, orient='index', columns=colNames)	
>        Column A  Column B  Column C
> Row 1         1         2         3
> Row 2         4         5         6
> Row 3         7         8         9

It’s worth noting that some versions of Pandas do not include the columns option. In these cases we can assign the list of names directly to the columns attribute of the DataFrame object to get the same result. After you convert your dictionary to a Pandas DataFrame, you would add your own column names using a code like this:

colNames = ["Column A", "Column B", "Column C"]
df.columns = colNames
print(df)
>        Column A  Column B  Column C
> Row 1         1         2         3
> Row 2         4         5         6
> Row 3         7         8         9

You may use the following template to convert a dictionary to Pandas DataFrame:

import pandas as pd

my_dict = {key:value,key:value,key:value,...}
df = pd.DataFrame(list(my_dict.items()),columns = ['column1','column2'])

In this short tutorial, I’ll review the steps to convert a dictionary to Pandas DataFrame. I’ll also share the code to create the following tool to convert your dictionary to a DataFrame:

How to Convert Dictionary to Pandas DataFrame

Steps to Convert a Dictionary to Pandas DataFrame

Step 1: Gather the Data for the Dictionary

To start, gather the data for your dictionary.

For example, I gathered the following data about products and prices:

Product Price
Computer 1500
Monitor 300
Printer 150
Desk 250

Step 2: Create the Dictionary

Next, create the dictionary.

For our example, you may use the following code to create the dictionary:

my_dict = {'Computer':1500,'Monitor':300,'Printer':150,'Desk':250}

print (my_dict)

Run the code in python, and you’ll get this dictionary:

Dictionary in Python

Step 3: Convert the Dictionary to a DataFrame

Finally, convert the dictionary to a DataFrame using this template:

import pandas as pd

my_dict = {key:value,key:value,key:value,...}
df = pd.DataFrame(list(my_dict.items()),columns = ['column1','column2'])

For our example, here is the complete Python code to convert the dictionary to Pandas DataFrame:

import pandas as pd

my_dict = {'Computer':1500,'Monitor':300,'Printer':150,'Desk':250}
df = pd.DataFrame(list(my_dict.items()),columns = ['Products','Prices'])

print (df)

Run the code, and you’ll get the DataFrame below:

DataFrame in Python

You can further verify that you got a DataFrame by adding print (type(df)) at the bottom of the code:

import pandas as pd

my_dict = {'Computer':1500,'Monitor':300,'Printer':150,'Desk':250}
df = pd.DataFrame(list(my_dict.items()),columns = ['Products','Prices'])

print (df)
print (type(df))

As you can see, the dictionary got converted to Pandas DataFrame:

Dictionary to a DataFrame

Tool to Convert Dictionaries

In the last section of this tutorial, I’ll share with you the code to create a tool to convert dictionaries to DataFrames.

The code is based on the tkinter module that can be used to create a GUI in python.

Here is the complete code:

import pandas as pd
import tkinter as tk

root= tk.Tk()

canvas1 = tk.Canvas(root, width = 500, height = 500,  relief = 'raised')
canvas1.pack()

label1 = tk.Label(root, text='Convert Dictionary to DataFrame')
label1.config(font=('helvetica', 14))
canvas1.create_window(250, 25, window=label1)

label2 = tk.Label(root, text='Input Your Dictionary:')
label2.config(font=('helvetica', 10))
canvas1.create_window(250, 100, window=label2)

entry1 = tk.Entry (root, width = 70) 
canvas1.create_window(250, 140, window=entry1)

def getDataFrame ():
    
    my_dict = str(entry1.get())
    my_dict = eval(my_dict)
    df = pd.DataFrame(list(my_dict.items()),columns= ['Products','Prices'])
    print (df)
    
    label3 = tk.Label(root, text=df,font=('helvetica', 10, 'bold'))
    canvas1.create_window(250, 270, window=label3)
    
button1 = tk.Button(text='Get DataFrame', command=getDataFrame, bg='brown', 
fg='white', font=('helvetica', 9, 'bold')) canvas1.create_window(250, 180, window=button1)

root.mainloop()

Once you run the code, you’ll see this GUI:

tkinter GUI

{'Computer':1500,'Monitor':300,'Printer':150,'Desk':250}

How to Convert Dictionary to Pandas DataFrame

Finally, click on the red button to get the dataframe:

Dictionary to Pandas DataFrame

Tags
Submitted by shiksha.dahiya on February 16, 2021

Shiksha is working as a Data Scientist at iVagus. She has expertise in Data Science and Machine Learning.

About

Elix is a premium wordpress theme for portfolio, freelancer, design agencies and a wide range of other design institutions.