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

which unfortunately only gives me:

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



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

Leave a Reply

Your email address will not be published. Required fields are marked *