简体   繁体   中英

Writing Python Dictionary with multiple keys to CSV

How do I write a dictionary with multiple keys to csv vertically as shown in image? I can only use native packages such as csv. I am getting this output but I need this as an output .

Below it the snippet (tried with different looping techniques) but didn't seem to work !

import csv

my_file = open("test.csv", mode="w")
sorted_keys = sorted(csv_dict)

writer = csv.DictWriter(my_file, fieldnames = sorted_keys, restval='')
writer.writeheader()
writer.writerow(csv_dict)

Answering my own question, but this snippet worked

csv_file = 'file.csv'
with open(csv_file, 'wb') as fd:
writer = csv.writer(fd, delimiter=',')

keys = sorted(dictionary) 
# Format headers for aesthetics
headers = [' {} '.format(key) for key in keys]
writer.writerow(headers)

# Format data to create convenient csv format
csv_data = itertools.izip_longest(*(dictionary[key] for key in keys),
                                  fillvalue='     ')
writer.writerows(csv_data)

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