How to Create a List of Dictionaries from an Excel Column in Python?

Estimated read time 2 min read

To create a list of dictionaries from an Excel column in Python, you can use the pandas library to read the Excel file and convert it into a DataFrame, and then convert the DataFrame into a list of dictionaries. Here’s an example code that reads an Excel file named data.xlsx, extracts the contents of the first column, and converts it into a list of dictionaries:

import pandas as pd

# read the Excel file into a DataFrame
df = pd.read_excel('data.xlsx')

# extract the first column as a Series
column1 = df.iloc[:, 0]

# convert the Series into a list of dictionaries
dict_list = column1.to_dict(orient='records')

# print the list of dictionaries

In this example, we first import the pandas library. Then we use the pd.read_excel() function to read the contents of the Excel file data.xlsx into a DataFrame df. We use the iloc[] method to extract the first column of the DataFrame as a Series column1.

Finally, we use the to_dict() method to convert the Series into a list of dictionaries. The orient='records' parameter specifies that each row of the Series should be converted into a separate dictionary, with the keys of the dictionary being the column names of the DataFrame.

Note that the resulting list of dictionaries will contain only one key-value pair, where the key is the column name and the value is the contents of the corresponding cell in the Excel column. If you want to include more columns from the Excel file in the resulting list of dictionaries, you need to extract them using the iloc[] method and include them in the to_dict() method.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply