Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

Python Dictionary to CSV

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...