how to export print result to excel using python (for loop)

Question:

Below is my code and need to generate the result into excel using xlsx writer module:

a=3
mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
for i,l in zip(mylist,range(a)):
    print('r')
    print('Result : {0}'.format(l))
    for key,value in i.items():
          print(key,':',value)
Asked By: Happy Man

||

Answers:

I don’t know what extension you are talking about when you say Excel. But you can use .csv file to write to a file.

It should go something like this.

with open('out.csv','w') as f:
   for key,value in i.items():
       print(key,',',value)

or you can convert the dictionary into a Pandas Dataframe and export it as .xlsx file using to_excel() function built-in to Pandas. https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html

Answered By: batuhaneralp

you can use the pandas library

import pandas as pd

a = 3
mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]

# Create an empty dataframe
df = pd.DataFrame()

for i, l in zip(mylist, range(a)):
    result = 'Result : ' + str(l)
    for key, value in i.items():
        # Append the result and key-value pairs to the dataframe
        df = df.append({'Result': result, 'Key': key, 'Value': value}, ignore_index=True)

# Save the dataframe to an Excel file
df.to_excel('output.xlsx', index=False)

enter image description here

Answered By: Mohammed Chaaraoui
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.