Convert txt python dictionary file to csv data file?

Question:

I have a text file with 300,000 records. A sample is below:

{'AIG': 'American International Group', 'AA': 'Alcoa Corporation', 'EA': 'Electronic Arts Inc.'}

I would like to export the records into a csv file like this:

enter image description here

I tried the following, but it does not put any line breaks between the records. So in excel, the 300,000 records are in two rows, which doesn’t fit everything (16,000 column limit in Excel).

import pandas as pd

read_file = pd.read_csv (r'C:...input.txt')
read_file.to_csv (r'C:...output.csv', index=None)
Asked By: HTMLHelpMe

||

Answers:

You can try:

import pandas as pd
from ast import literal_eval

with open('your_file.txt', 'r', encoding='utf-8') as f_in:
    data = literal_eval(f_in.read())

df = pd.DataFrame([{'Ticker': k, 'Name': v} for k, v in data.items()])
print(df)

# to save to CSV:
#df.to_csv('out.csv', index=False)

Prints:

  Ticker                          Name
0    AIG  American International Group
1     AA             Alcoa Corporation
2     EA          Electronic Arts Inc.
Answered By: Andrej Kesely
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.