简体   繁体   English

使用 python 将字典中的键和值写入 csv

[英]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.我有一个字典,有两个键是“text1”和“text2”,特征是键“text1”有一个重复的字符“A”但是当我更新字典时可以更改两次出现“A”之间的元素数量“数据”有时。 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: 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:

在此处输入图像描述

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

To write to csv file from your data dictionary, you can use this example:要从data字典写入 csv 文件,可以使用以下示例:

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 :创建result.csv

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

Screenshot:截屏:

在此处输入图像描述

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

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