Hoang Minh Nguyen
Hoang Minh Nguyen

Reputation: 91

write key and value from dictionary to csv with python

I have a dictionary with 2 keys are "text1" and "text2", the characteristic is key "text1" has a repeated character "A" but the number of element between 2 occurrence of "A" can be changed when I update dictionary "data" sometimes. I want to writer a header row in csv with all values from "A" to value before next "A", and the value from "text2" will be matched with column from header as below expected result in csv:

enter image description here

import csv
data={
    "text1":("A","mouse","cat","A","mouse","cat","A","mouse","cat"),
    "text2":(1,2,3,4,5,6,7,8,9)
}


with open("result.csv","w") as f:
    writer=csv.writer(f,delimiter=',',lineterminator='\n')
    writer_inline=csv.writer(f,delimiter=',',lineterminator=',')
    for i in range(0,len(data["text1"])):
        writer_inline.writerow([data["text1"][i]])
        if data["text1"][i]=="A" and i>1:
            continue

with open("result.csv","r") as f:
    print(f.read())

Upvotes: 2

Views: 60

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195593

To write to csv file from your data dictionary, you can use this example:

import csv

data = {
    "text1": ("A", "mouse", "cat", "A", "mouse", "cat", "A", "mouse", "cat"),
    "text2": (1, 2, 3, 4, 5, 6, 7, 8, 9),
}

tmp = {}
for k, v in zip(data["text1"], data["text2"]):
    tmp.setdefault(k, []).append(v)

with open("result.csv", "w") as f_out:
    writer = csv.writer(f_out)
    writer.writerow(tmp.keys())
    writer.writerows(zip(*tmp.values()))

Creates result.csv:

A,mouse,cat
1,2,3
4,5,6
7,8,9

Screenshot:

enter image description here

Upvotes: 1

Related Questions