How to create a pandas DataFrame using a list of dictionaries?


DataFrame is a two-dimensional pandas data structure, which is used to represent the tabular data in the rows and columns format.

We can create a pandas DataFrame object by using the python list of dictionaries. If we use a dictionary as data to the DataFrame function then we no need to specify the column names explicitly.

Here we will create a DataFrame using a list of dictionaries, in the below example.

Example

# Creating list of dictionaries
li = [{'i': 10, 'j': 20, 'k': 30},{'i': 8, 'j': 40, 'k': 60},{'i': 6, 'j': 60, 'k': 90}]

# creating dataframe
df = pd.DataFrame(l, index=[100,101,102])

#display the output
print(df)

Explanation

List li has a list of dictionaries, here the keys of each dictionary are represented as column labels, and values of the dictionary are represented as data(values) of DataFrame. If you want to change the default row labels then you can use index parameters like the above example.

Output

      i   j   k
100  10  20  30
101  8   40  60
102  6   60  90

The output of the DataFrame object ‘df’ is shown in the above block, the column labels are automatically taken by dictionary key and row labels are defined by using index parameters.

Example

# Creating list of dictionaries
li = [{'A':10, 'B':89, 'C':43},{'A': 88, 'J': 50, 'B': 7},{'A':9, 'B':8, 'C':12}]


# creating dataframe
df = pd.DataFrame(li)

#display the output
print(df)

Explanation

In this following example, the keys in the list of dictionaries are not the same, due to this we will get the missing data as an element in the resulting DataFrame Object.

Output

    A   B     C    J
0  10  89  43.0   NaN
1  88   7   NaN  50.0
2   9   8  12.0   NaN

We can see the NaN values in the above DataFrame object. Because there is no data defined in the list of dictionaries for column J.

Updated on: 18-Nov-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements