Open In App

How to convert Dictionary to Pandas Dataframe?

Let’s discuss how to convert Python Dictionary to Pandas Dataframe. We can convert a dictionary to a Pandas dataframe by using the pd.DataFrame.from_dict() class-method.

Convert Dictionary to Pandas Dataframe In Python Examples

Below are the ways by which we can convert dictionary to Pandas Dataframe in Python:



Using Pandas Constructor (pd.DataFrame())

In this example, we are using Pandas constructor pd.DataFrame().




import pandas as pd
 
data = {'name': ['nick', 'david', 'joe', 'ross'],
        'age': ['5', '10', '7', '6']}
new = pd.DataFrame.from_dict(data)
 
new

Output



    name age
0 nick 5
1 david 10
2 joe 7
3 ross 6

Convert a Dictionary Into a DataFrame

In this example, we are using list of dictionary to convert the dictionary into a Pandas Dataframe.




import pandas as pd
 
data = [{'area': 'new-hills', 'rainfall': 100, 'temperature': 20},
        {'area': 'cape-town''rainfall': 70, 'temperature': 25},
        {'area': 'mumbai''rainfall': 200'temperature': 39}]
 
df = pd.DataFrame.from_dict(data)
 
df

Output

         area  rainfall  temperature
0 new-hills 100 20
1 cape-town 70 25
2 mumbai 200 39

Converting Dictionary to DataFrame With Orient=‘Index’

In this example, we are using the orient parameter to change the orientation of the dataframe from column to index




import pandas as pd
 
data = {'area': ['new-hills', 'cape-town', 'mumbai'],
        'rainfall': [100, 70, 200],
        'temperature': [20, 25, 39]}
 
df = pd.DataFrame.from_dict(data, orient='index')
df
print(df)

Output

         area rainfall temperature
0 new-hills 100 20
1 cape-town 70 25
2 mumbai 200 39

Converting dictionary with keys and list of values with different lengths

In this example, we are converting dictionary with keys and list of values with different lengths to Pandas Dataframe.




import pandas as pd
 
# Your dictionary with keys and lists of values
data = {
    'key1': [1, 2, 3],
    'key2': [4, 5],
    'key3': [6, 7, 8, 9]
}
 
# Convert the dictionary to a pandas DataFrame
df = pd.DataFrame(list(data.items()), columns=['Key', 'Values'])
 
# Display the DataFrame
print(df)

Output

    Key      Values
0 key1 [1, 2, 3]
1 key2 [4, 5]
2 key3 [6, 7, 8, 9]

Article Tags :