Reputation: 326
I want to write this following python dictionary of lists with different length to csv.
dic = {'a': ['ACI', 'BBY', 'AMRX'], 'b': ['ABM', 'AG']}
The expected output is:
Upvotes: 2
Views: 2122
Reputation: 120469
Use the csv
module:
# convert your dict to a list
lst = [[k] + v for k, v in dic.items()]
# write all rows at once
with open('test.csv', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
writer.writerows(lst)
>>> %cat 'test.csv'
a,ACI,BBY,AMRX
b,ABM,AG
Upvotes: 3
Reputation: 5518
There is no "equal length" requirement in python's vanilla csv
module. Simply iterating over the dictionary and outputting the rows should do the trick
import csv
dic = {'a': ['ACI', 'BBY', 'AMRX'], 'b': ['ABM', 'AG']}
with open('/path/to/output.csv', 'w', newline='') as f:
writer = csv.writer(f)
# python `dicts` are unordered, but assuming you
# want the rows in key-alphabetical order
for key, vals in sorted(dic.items(), key=lambda k: k[0]):
writer.writerow([key] + vals)
If however, you want to ensure lines are of equal length, you can first run a pass to figure out the max length:
max_len = max(len(val) for val in dic.values())
then fill accordingly when writing out each row
writer.writerow([key] + vals + [None] * (max_len - len(vals)))
Upvotes: 1
Reputation: 23815
just loop over the values of the dict and write them to a file.
No external library is required.
dic = {'a': ['ACI', 'BBY', 'AMRX'], 'b': ['ABM', 'AG']}
with open('out.csv', 'w') as f:
for key, values in dic.items():
f.write(key + ',' + ','.join(values) + '\n')
out.csv
a,ACI,BBY,AMRX
b,ABM,AG
Upvotes: 1
Reputation: 480
import pandas as pd
dic = {'a': ['ACI', 'BBY', 'AMRX'], 'b': ['ABM', 'AG']}
df = pd.DataFrame.from_dict(dic, orient='index') #Convert dict to df
print(df)
df.to_csv("final.csv",header=False) #Convert df to csv
Upvotes: 4