简体   繁体   中英

write data from dictionary to csv by python

I have a dictionary as below which has repeated item name, the difference is the value of each part name. i want to write those info to csv with expected result is:

在此处输入图像描述

    import csv
dict={
    'test':['part_name','test1','test2','test3','part_name','test1','test2','test3'],
    'value':['partA','12','55','109','partB','14','54','106'],
    'lcl':['lcl','10','50','100','lcl','10','50','100'],
    'ucl':['ucl','18','60','115','ucl','18','60','115'],
}
tmp={}
for k,v1,v2,v3 in zip(dict["test"],dict["value"],dict["lcl"],dict["ucl"]):
    tmp.setdefault(k, []).append([v1,v2,v3])
print(tmp)
with open('table.csv','w') as f:
    writer_inline = csv.writer(f, delimiter=',', lineterminator=',')
    writer = csv.writer(f, delimiter=',', lineterminator='\n')
    writer.writerow(tmp.keys())
    writer.writerows(zip(*tmp.values()))

Try the below code to get your desired csv. I would recommend not to use dict as name for your dictionary. I have changed it to d :

import csv
d = {
    'test':['part_name','test1','test2','test3','part_name','test1','test2','test3'],
    'value':['partA','12','55','109','partB','14','54','106'],
    'lcl':['lcl','10','50','100','lcl','10','50','100'],
    'ucl':['ucl','18','60','115','ucl','18','60','115'],
}

headers = d['test'][:len(set(d['test']))]
size = len(headers)
d.pop('test', None)

parts = []
for i in d:
    parts += [[d[i][j:(j+size)] for j in range(0, len(d['value']), size)]]

rows = []
for part in list(zip(*parts)):
    rows += part

with open('table.csv','w') as f:
    writer = csv.writer(f, delimiter=',', lineterminator='\n')
    writer.writerow(headers)
    writer.writerows(rows)

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