简体   繁体   中英

How to write a dictionary with multiple keys, each with multiple values to a csv in Python?

I have a dictionary that looks like this...

cla_1results= {"Tom":[1,7,4],"Dunc":[3,9,4],"Jack":[1,3,5]}

I want to write this dictionary to a csv so that it is in the following format

Don't have the rep to post images but it would be something like this...

Tom,  1, 7, 4
Dunc  3, 9, 4
Jack  1, 3, 5

Nothing I've tried has worked. My recent effort is below but I'm a real beginner with Python and programming in general.

import csv

cla_1results= {"Tom":[1,7,4],"Dunc":[3,9,4],"Jack":[1,3,5]}
cla_2results = {"Jane":[1,7,4],"Lynda":[3,9,4],"Dave":[1,3,5]}
cla_3results = {"Gemma":[1,7,4],"Steve":[3,9,4],"Jay":[1,3,5]}

b = open ('test.csv','w')
a = csv.writer(b)
data = cla_1results= {"Tom":[1,7,4],"Dunc":[3,9,4],"Jack":[1,3,5]}
a.writerows(data)
b.close()

which unfortunately only gives me:

T, o, m
D, u, n, c
J, a, c, k

etc

This should work, you just needed a list to generate csv file, so it can be generated on the fly as well.

import csv
cla_1results= {"Tom":[1,7,4],"Dunc":[3,9,4],"Jack":[1,3,5]}
with open('test.csv', 'wb') as csvfile:

        writer = csv.writer(csvfile, delimiter=',')

        for key,value in cla_1results.iteritems():
                writer.writerow([key]+value)

You can use the DataFrame.from_dict() classmethod to convert dict to DataFrame and then can use to_csv to convert the dataframe to csv. I have used header=False to strip off the headers.

from pandas import DataFrame

cla_1results = {"Tom": [1, 7, 4], "Dunc": [3, 9, 4], "Jack": [1, 3, 5]}

df = DataFrame.from_dict(cla_1results, orient='index')

print(df.to_csv(header=False))

Dunc,3,9,4
Jack,1,3,5
Tom,1,7,4

Try:

import csv

with open('test.csv', 'wb') as csvfile:
    c = csv.writer(csvfile)
    line = []
    for key, value in cla.iteritems():
        line.append(key)
        for i in value:
            line.append(i)
        c.writerow(line)
data = {"Tom":[1,7,4],"Dunc":[3,9,4],"Jack":[1,3,5]}
with open('test.csv', 'w') as f:
    for k, vals in data.items():
        line = ','.join([k] + map(str, vals)) + '\n'
        f.write(line)

One of many ways to do it:

import csv

cla_1results = {
    "Tom": [1, 7, 4],
    "Dunc": [3, 9, 4],
    "Jack": [1, 3, 5]
}

with open("test.csv", 'w+') as file:
    writer = csv.writer(file)

    for name in cla_1results:
        writer.writerow([name, ] + [i for i in cla_1results[name]])

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