Python 字典转 CSV

发布于 2024-12-19 00:40:07 字数 1145 浏览 0 评论 0原文

我已经编写了将 CSV 读入 python 字典的代码,效果很好。我正在尝试将字典恢复为 CSV。我写了以下内容:

import csv

itemDict={}

listReader = csv.reader(open('/Users/broberts/Desktop/Sum_CSP1.csv','rU'), delimiter = ',', quotechar='|')

for row in listReader:
    fID = row[0]
    fClassRange = row[1]
    fArea = row[2]

    if itemDict.has_key(fID):
        itemDict[fID][fClassRange]=fArea
    else:
        itemDict[fID] = {'5.0 to 5.25':'','5.25 to 5.5':'','5.5 to 5.75':'','5.75 to 6.0':'','6.0 to 6.25':'','6.25 to 6.5':'','6.5 to 6.75':'','6.75 to 7.0':'','7.0 to 7.25':'','7.25 to 7.5':'','7.5 to 7.75':'','7.75 to 8.0':'','8.0 to 8.25':'',}
        itemDict[fID][fClassRange]=fArea

listWriter = csv.writer(open('/Users/broberts/Desktop/Sum_CSP1_output.csv', 'wb'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)

for a in itemDict:
    print a
    listWriter.writerow(a)

在最后一个块中,listWriter 不会向 CSV 写入任何内容,尽管它会打印 a.txt 文件。我相信这与字典无序有关。我确实需要写出 fID 和与每个 fID 关联的每个键(fClassRange 例如“5.0 到 5.25”),然后将与每个 fClassRange 关联的值 fArea 写到 CSV 中,但我还没有写出那么远我的代码,因为我什至不知道如何写出 fID。

我研究过使用 DictWriter,但我不知道如何告诉它所需的字段名是什么。

I have written code to read a CSV into a python dictionary, which works fine. I'm trying to get the dictionary back to a CSV. I have written the following:

import csv

itemDict={}

listReader = csv.reader(open('/Users/broberts/Desktop/Sum_CSP1.csv','rU'), delimiter = ',', quotechar='|')

for row in listReader:
    fID = row[0]
    fClassRange = row[1]
    fArea = row[2]

    if itemDict.has_key(fID):
        itemDict[fID][fClassRange]=fArea
    else:
        itemDict[fID] = {'5.0 to 5.25':'','5.25 to 5.5':'','5.5 to 5.75':'','5.75 to 6.0':'','6.0 to 6.25':'','6.25 to 6.5':'','6.5 to 6.75':'','6.75 to 7.0':'','7.0 to 7.25':'','7.25 to 7.5':'','7.5 to 7.75':'','7.75 to 8.0':'','8.0 to 8.25':'',}
        itemDict[fID][fClassRange]=fArea

listWriter = csv.writer(open('/Users/broberts/Desktop/Sum_CSP1_output.csv', 'wb'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)

for a in itemDict:
    print a
    listWriter.writerow(a)

In the last block, listWriter will not write anything to the CSV though it will print a. I believe this has something to do with a dictionary being unordered. I really need to write out the fID and each of the keys associated with each fID (fClassRange ex. "5.0 to 5.25") and then the value fArea associated with each fClassRange to the CSV, but I haven't even gotten that far in my code since I can't figure out how to write out even the fID.

I looked into using DictWriter, but I can't figure out how to tell it what the required fieldnames are.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

随心而道 2024-12-26 00:40:07

示例数据:

mydict = [{"col1": 1000, "col2": 2000}, {"col1": 3000, "col2": 4000}]

使用 pandas 将字典列表转换为 CSV 的单行代码:

import pandas as pd

pd.DataFrame(mydict).to_csv('out.csv', index=False)

结果:

col1,col2
1000,2000
3000,4000

Sample data:

mydict = [{"col1": 1000, "col2": 2000}, {"col1": 3000, "col2": 4000}]

One-liner for converting a list of dicts to CSV, using pandas:

import pandas as pd

pd.DataFrame(mydict).to_csv('out.csv', index=False)

Results:

col1,col2
1000,2000
3000,4000
随梦而飞# 2024-12-26 00:40:07

默认编写器需要一个列表,这就是为什么它不适合您。要使用 dictwriter,只需将 listwriter = 行更改为:

with open('/Users/broberts/Desktop/Sum_CSP1_output.csv', 'wb') as outfile:
    listWriter = csv.DictWriter(
       outfile,
       fieldnames=itemDict[itemDict.keys()[0]].keys(),
       delimiter=',',
       quotechar='|',
       quoting=csv.QUOTE_MINIMAL
    )

或者,您可以将 fieldnames 设置为 fieldnames=['任意','list' ,'of','keys'] 如果您知道字段应该是什么。

The default writer expects a list, which is why it won't work for you. To use the dictwriter, just change your listwriter = line to this:

with open('/Users/broberts/Desktop/Sum_CSP1_output.csv', 'wb') as outfile:
    listWriter = csv.DictWriter(
       outfile,
       fieldnames=itemDict[itemDict.keys()[0]].keys(),
       delimiter=',',
       quotechar='|',
       quoting=csv.QUOTE_MINIMAL
    )

Or, you can just set fieldnames to be fieldnames=['arbitrary','list','of','keys'] if you know what the fields are supposed to be.

失而复得 2024-12-26 00:40:07

writerows 的示例:

import csv

def main():

    results = [
            {'File': 'test.txt', 'Temperature': 32.33, 'Day': 'Monday'},
            {'File': 'test2.txt', 'Temperature': 44.33, 'Day': 'Tuesday'},
            {'File': 'test3.txt', 'Temperature': 44.23, 'Day': 'Sunday'}
        ]

    with open('results.csv', 'w') as f:  
        w = csv.DictWriter(f, results[0].keys())
        w.writeheader()        
        w.writerows(results)                    
        
if __name__ == "__main__":
    main()  

这将导致 结果.csv

File,Temperature,Day
test.txt,32.33,Monday
test2.txt,44.33,Tuesday
test3.txt,44.23,Sunday

An example with writerows:

import csv

def main():

    results = [
            {'File': 'test.txt', 'Temperature': 32.33, 'Day': 'Monday'},
            {'File': 'test2.txt', 'Temperature': 44.33, 'Day': 'Tuesday'},
            {'File': 'test3.txt', 'Temperature': 44.23, 'Day': 'Sunday'}
        ]

    with open('results.csv', 'w') as f:  
        w = csv.DictWriter(f, results[0].keys())
        w.writeheader()        
        w.writerows(results)                    
        
if __name__ == "__main__":
    main()  

which will result in results.csv of:

File,Temperature,Day
test.txt,32.33,Monday
test2.txt,44.33,Tuesday
test3.txt,44.23,Sunday
裸钻 2024-12-26 00:40:07

这就是我使用的,它简单并且适合我。
当你只有一个字典时,使用这个

my_dict = {"tester": 1, "testers": 2}
with open('mycsvfile.csv', 'wb') as f:  
    w = csv.DictWriter(f, my_dict.keys())
    w.writerow(dict((fn,fn) for fn in my_dict.keys()))
    w.writerow(my_dict)

$ cat mycsvfile.csv
testers,tester
2,1

当你有一个字典列表时,就像你从 SQL 查询中得到的一样,你确实喜欢这样。

my_dict = ({"tester": 1, "testers": 2},{"tester": 14, "testers": 28})
with open('mycsvfile.csv', 'wb') as f:  
    w = csv.DictWriter(f, my_dict[0].keys())
    w.writerow(dict((fn,fn) for fn in my_dict[0].keys()))
    w.writerows(my_dict)

cat mycsvfile.csv
testers,tester
2,1
28,14

This is what i use, its simple and works fine for me.
when you have only one dictionary, use this

my_dict = {"tester": 1, "testers": 2}
with open('mycsvfile.csv', 'wb') as f:  
    w = csv.DictWriter(f, my_dict.keys())
    w.writerow(dict((fn,fn) for fn in my_dict.keys()))
    w.writerow(my_dict)

$ cat mycsvfile.csv
testers,tester
2,1

When you have a list of dictionaries, like what you get from SQL queries, you do like this.

my_dict = ({"tester": 1, "testers": 2},{"tester": 14, "testers": 28})
with open('mycsvfile.csv', 'wb') as f:  
    w = csv.DictWriter(f, my_dict[0].keys())
    w.writerow(dict((fn,fn) for fn in my_dict[0].keys()))
    w.writerows(my_dict)

cat mycsvfile.csv
testers,tester
2,1
28,14
我很坚强 2024-12-26 00:40:07

对于后代:

您应该使用 iteritems() 来迭代字典,因此最后一部分变成

for name, values in itemDict.iteritems():
    print values
    listWriter.writerow(values)

For posterity:

You should use iteritems() to iterate over a dictionary, so the last part becomes

for name, values in itemDict.iteritems():
    print values
    listWriter.writerow(values)
深爱不及久伴 2024-12-26 00:40:07

对我有帮助的是在打开文件时添加 newline="" 参数。

例如:

with open("sample.csv", "w", newline="") as outfile:
    writer = csv.writer(outfile)
    for num in range(0, 10):
        writer.writerow([num])

src

What helped me was adding newline="" argument when opening file.

ex:

with open("sample.csv", "w", newline="") as outfile:
    writer = csv.writer(outfile)
    for num in range(0, 10):
        writer.writerow([num])

src

爱*していゐ 2024-12-26 00:40:07
d = [{'a': 1, 'b': 2},{'a': 3, 'b': 4}]

with open('csv_file.csv', 'w', newline='\n') as f:
    w = csv.DictWriter(f, d[0].keys())
    w.writeheader()
    for i in d:
        w.writerow(i)

得到你

a,b
1,2
3,4
d = [{'a': 1, 'b': 2},{'a': 3, 'b': 4}]

with open('csv_file.csv', 'w', newline='\n') as f:
    w = csv.DictWriter(f, d[0].keys())
    w.writeheader()
    for i in d:
        w.writerow(i)

gets you

a,b
1,2
3,4
2024-12-26 00:40:07

最简单的方法

您可以将字典转换为Dataframe并将其写入csv
例如

import pandas as pd
my_dict = {"tester": 1, "testers": 2}
df=pd.DataFrame(my_dict,index=[0])
df.to_csv("path and name of your csv.csv")

输出

   tester  testers
0       1        2

Easiest Way

You can convert the dictionary into Dataframe and write it to csv
Eg

import pandas as pd
my_dict = {"tester": 1, "testers": 2}
df=pd.DataFrame(my_dict,index=[0])
df.to_csv("path and name of your csv.csv")

output

   tester  testers
0       1        2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文