简体   繁体   English

Python 用 header 将字典写入 csv

[英]Python write dictionary to csv with header

I want to write a specific python dictionary to csv with header.我想用 header 写一个特定的 python 字典到 csv。 I have looked at other questions but none of them have the similar dictionary structure as mine:我查看了其他问题,但没有一个与我的字典结构相似:

myDic = { "a" : 1, "b" : 2, "c" : 15}

header = ["word", "count"]

with open('myFile.csv', 'w', encoding='utf-8-sig') as f:
    w = csv.DictWriter(f, header)
    w.writeheader()
    w.writerow(myDic)

What I got is only word,count in my CSV file.我得到的只是一个word,count I am using python 3.我正在使用 python 3。

You can't use DictWriter in that way, it is designed for key=column_header and value=[row_values] .您不能以这种方式使用DictWriter ,它是为key=column_headervalue=[row_values]设计的。

You can instead iterate your dictionary and use csv.writerow您可以改为迭代您的字典并使用csv.writerow

import csv

myDic = { "a" : 1, "b" : 2, "c" : 15}

header = ["word", "count"]

with open('myFile.csv', 'w', encoding='utf-8-sig') as f:
    w.writerow(header)
    for k, v in myDic.items():
        w.writerow([k, v])

or as juanpa.arrivillaga pointed out you can writerows directly on the .items() .或者正如 juanpa.arrivillaga 指出的那样,您可以直接在writerows .items()上写入。

with open('myFile.csv', 'w', encoding='utf-8-sig') as f:
    w.writerow(header)
    w.writerows(myDic.items())

However, storing your information for your csv in a dictionary in this way is very limiting since it can only ever be two columns so ensure that is an acceptable choice before continuing down this path.但是,以这种方式将 csv 的信息存储在字典中是非常有限的,因为它只能是两列,因此在继续沿此路径之前确保这是一个可接受的选择。

You are trying to write the entire dictionary as a row.您正在尝试将整个字典写成一行。 Instead, write each row separately.相反,分别编写每一行。

Please see here for more details:请在此处查看更多详细信息:

https://docs.python.org/3/library/csv.html#csv.DictWriter https://docs.python.org/3/library/csv.html#csv.DictWriter

As an example please see the following usage:作为示例,请参阅以下用法:

import csv

myDic = { "a" : 1, "b" : 2, "c" : 15}
with open('myFile.csv', 'w', newline='') as csvfile:
    fieldnames = ['word', 'count']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for key in myDic:
        writer.writerow({'word': key, 'count': myDic[key]})

Let me know if this helps.让我知道这是否有帮助。 I didn't test the code... but I may before you see the answer.我没有测试代码......但我可能会在你看到答案之前。

Edit Yeah tested, seems to work fine.编辑是的,经过测试,似乎工作正常。 Best of luck!祝你好运!

This should work这应该工作

import csv

myDic = { "a" : 1, "b" : 2, "c" : 15}

header = ["word", "count"]

with open('myFile.csv', 'w', encoding='utf-8-sig') as f:
    writer = csv.writer(f)
    writer.writerow(header) # write the header
    for k,v in myDic.items():
        writer.writerow([k,v])

I am a Pandas person so I will give the way of doing this using Pandas我是 Pandas 人,所以我将给出使用 Pandas 的方法

import pandas as pd
myDic = { "a" : 1, "b" : 2, "c" : 15}
header = ["word", "count"]

df = pd.DataFrame.from_dict(myDic, orient='index').reset_index()
df.columns = header
df.to_csv('word_count.csv', index=False)

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

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