简体   繁体   中英

How to write a dictionary of lists with different length to csv?

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:

预期输出

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

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

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

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM