簡體   English   中英

使用 python 將字典中的鍵和值寫入 csv

[英]write key and value from dictionary to csv with python

我有一個字典,有兩個鍵是“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:

在此處輸入圖像描述

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

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

創建result.csv

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

截屏:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM