0

I have an excel file with two column and I would like to convert it to this format

l = [{'a': 1, 'b': 2}, 
     {'a': 4, 'b': 3}] 

a : refers to the first column header and b refers to the second column header.

I imported the excel file using Pandas as

dataframe = pd.read_excel('sample.xlsx')

I tried by creating empty list and set data frame to that empty list but it is not working.

jpp
  • 159,742
  • 34
  • 281
  • 339
tita
  • 107
  • 1
  • 5

2 Answers2

0

If the Excel sheet has strictly two columns with values in every cell within the columns,

You can save it as a .csv file and parse it as such:

results = []
with open("your-file.csv") as file:
    for line in file:
        separated = line.split(',')
        results.append( { 'a':separated[0], 'b':separated[1] } )
Gigaflop
  • 390
  • 1
  • 13
  • Do you really need to save the file as csv? – mad_ Jul 30 '18 at 20:58
  • @mad_ If you want this method to work, then yes, a copy of the excel sheet must be saved as a `.csv`. I prefer doing things this way because it requires less libraries and is simpler for me to manage. – Gigaflop Jul 31 '18 at 12:07
0

You can convert the dataframe into dict

dataframe = pd.read_excel('sample.xlsx')
dataframe.to_dict('records')
mad_
  • 8,121
  • 2
  • 25
  • 40