Open In App

Convert Dictionary to DataFrame in Python with column names

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, the pandas library provides a powerful and flexible tool for working with tabular data through its DataFrame class. When creating a DataFrame from a dictionary, it’s common to set the keys of the dictionary as the column names of the resulting DataFrame. In this article, we will see how we can create a Pandas DataFrame from a dictionary as keys as column names.

Python DataFrame from Dictionary as Keys as Column Name

Below are some of the ways to achieve this task in Python:

  1. Using pd.DataFrame() Method
  2. Using list() method
  3. Using Series() method

Using pd.DataFrame() Method

In this example, a Python dictionary students containing names as keys and corresponding marks as values is converted to a Pandas DataFrame using pd.DataFrame(). The resulting DataFrame df displays the names and marks in tabular form with columns labeled ‘Name’ and ‘Marks’.

Python3




import pandas as pd
 
students = {"Shravan": 90, "Jeetu": 91, "Ram": 32, "Pankaj": 95}
 
# Convert the dictionary to a Pandas DataFrame
df = pd.DataFrame(students.items(), columns=['Name', 'Marks'])
 
print(df)


Output:

      Name  Marks
0 Shravan 90
1 Jeetu 91
2 Ram 32
3 Pankaj 95

Using list() method

In this example, a Python dictionary students with names as keys and corresponding marks as values is converted into a Pandas DataFrame using pd.DataFrame(list(students.items()), columns=['Name', 'Marks']). The resulting DataFrame df presents the names and marks in tabular form with columns labeled ‘Name’ and ‘Marks’.

Python3




import pandas as pd
 
students = {"Shravan": 90, "Jeetu": 91, "Ram": 32, "Pankaj": 95}
 
# Convert dictionary to DataFrame
df = pd.DataFrame(list(students.items()), columns=['Name', 'Marks'])
 
print(df)


Output:

      Name  Marks
0 Shravan 90
1 Jeetu 91
2 Ram 32
3 Pankaj 95

Using Series() method

In this example, a Python dictionary students with names as keys and corresponding scores as values is initially converted to a Pandas Series using pd.Series(students, name='Score'). Subsequently, the series is transformed into a DataFrame df with column names ‘Name’ and ‘Score’ by resetting the index and renaming the columns accordingly.

Python3




import pandas as pd
 
students = {"Shravan": 90, "Jeetu": 91, "Ram": 32, "Pankaj": 95}
 
# Convert dictionary to Series
series = pd.Series(students, name='Score')
 
# Convert series to DataFrame
df = pd.DataFrame(series)
df.reset_index(inplace=True)
df.columns = ['Name', 'Score']
 
print(df)


Output:

      Name  Score
0 Shravan 90
1 Jeetu 91
2 Ram 32
3 Pankaj 95


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads