简体   繁体   English

如何在Python中编写具有多个键的字典,每个键具有多个值到csv?

[英]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 我想将此字典写入csv,以便采用以下格式

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. 我最近的工作在下面,但是我是Python和程序设计的真正初学者。

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. 这应该可以工作,您只需要一个列表即可生成csv文件,因此它也可以即时生成。

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. 您可以使用DataFrame.from_dict()类方法将dict转换为DataFrame,然后可以使用to_csv将数据帧转换为csv。 I have used header=False to strip off the headers. 我已经使用header=False剥离标题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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