简体   繁体   中英

Write a Dictionary to a CSV file

I have a dictionary which contains the following:

{'Jim': ['1', '9', '5'], 'kim': ['8', '6', '0'], 'lim': ['10', '6', '1'], 'slim': ['8', '8', '2'], 'pimp': ['9', '9', '1'], 'sim': ['8', '7', '1']}

My question is: How do i write all of this into a CSV file?

It should write and appear something like this in the CSV file:

name xyz

name2 xyz

name 3 xyz

...

I have tried:

with open('file.csv', 'wb') as csvfile: 
    wr = csv.writer(csvfile)
    wr.writerow(DICTIONARY) 

You can iterate over the dictionary items and write one row at a time:

import csv

D = {'Jim': ['1', '9', '5'], 'kim': ['8', '6', '0'], 'lim': ['10', '6', '1'],
     'slim': ['8', '8', '2'], 'pimp': ['9', '9', '1'], 'sim': ['8', '7', '1']}

with open('file.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)      

    for name, items in D.items():    
        writer.writerow([name] + items)

Check csv.writer documentation here .
Note that Python dictionaries are unordered, ie this may not produce identical files on each run.

This code below enters the list of lists into separate columns (done by editting eugene's code)

with open("file.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)  
    for name, items in DICTIONARY.items():    
        writer.writerow([name] + items)

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