Pandas from_dict()

The from_dict() function in Pandas is used to convert a dictionary into a Pandas DataFrame.

Example

import pandas as pd

# sample dictionary
data_dict = {'A': [1, 2, 3],
             'B': [4, 5, 6],
             'C': [7, 8, 9]}

# convert dictionary to DataFrame
df = pd.DataFrame.from_dict(data_dict)

print(df)

'''
Output

   A  B  C
0  1  4  7
1  2  5  8
2  3  6  9
'''

from_dict() Syntax

The syntax of the from_dict() method in Pandas is:

pd.DataFrame.from_dict(data, orient='columns', dtype=None, columns=None)

from_dict() Arguments

The from_dict() method in Pandas has the following arguments:

  • data: the dictionary to convert
  • orient (optional): the type of orientation to use for the data
  • dtype (optional): data type to force for all columns
  • columns (optional): specifies the columns explicitly, if the keys of the passed dictionary should not be sorted

from_dict() Return Value

The from_dict() function returns a DataFrame object created from the input dictionary.


Example 1: Default Orientation

import pandas as pd

data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
             'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

# default orientation: 'columns'
df_default_orient = pd.DataFrame.from_dict(data_dict)

print(df_default_orient)

Output

   one  two
a  1.0    1
b  2.0    2
c  3.0    3
d  NaN    4

In this example, we used the default 'columns' orientation so that the indexes of the Series align with the index of the DataFrame, and the labels of the Series become the columns of the DataFrame.


Example 2: Specified Orientation

import pandas as pd

data_dict = {'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}

# Orient the DataFrame with index orientation
df_index_orient = pd.DataFrame.from_dict(data_dict, orient='index')

print(df_index_orient)

Output

   0  1  2
a  1  2  3
b  4  5  6
c  7  8  9

In this case, we used the 'index' orientation.So, the keys of the dictionary become the index of the DataFrame, and the list-like values become the rows.


Example 3: Specifying Columns Order

import pandas as pd

data_dict = {'one': [1, 2, 3], 'two': [4, 5, 6], 'three': [7, 8, 9]}

# create a DataFrame with specified columns order
df_specified_columns = pd.DataFrame.from_dict(data_dict, orient='index', columns=['three', 'two', 'one'])

print(df_specified_columns)

Output

       two  three  one
one      1      2    3
two      4      5    6
three    7      8    9

In this example, we explicitly defined the column order in the resulting DataFrame.

Note: We cannot use columns parameter with orient='columns'.