如何将CSV数据写入字典(或更好的处理方法)

kninwzqo  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(93)

我试图将CSV文件中的数据写入Python字典。我能得到我需要的数据,但我对如何输入字典一无所知。这些数据最终将被重写到一个新的CSV文件中,以便导入到其他系统中。
在下面的代码中,您将看到最终的目标CSV文件有两组头。首先使用writerow()来编写它们。相关的行被注解掉,以便在每次测试运行脚本时不再编写它们。
with open(bccsv, newline='') as csvfile:中的print语句在未注解时都能正常工作。
testdict.update("sonum": row['Order ID'])是我尝试编写第一个密钥对的,但它在冒号处抛出了语法错误。

import csv

bccsv = "order.csv"
fbcsv = "fbcsv.csv"
testdict = {"ordertype": "SO"}
#header1 = ["Flag","SONum","Status","CustomerName","CustomerContact","BillToName","BillToAddress","BillToCity","BillToState","BillToZip","BillToCountry","ShipToName","ShipToAddress","ShipToCity","ShipToState","ShipToZip","ShipToCountry","ShipToResidential","CarrierName","TaxRateName","PriorityId","PONum","VendorPONum","Date","Salesman","ShippingTerms","PaymentTerms","FOB","Note","QuickBooksClassName","LocationGroupName","OrderDateScheduled","URL","CarrierService","DateExpired","Phone,Email","Category","CF-Credit Key Approval ID","CarrierName","CF-Skynamo Comments"]
#header2 = ["Flag","SOItemTypeID","ProductNumber","ProductDescription","ProductQuantity","UOM","ProductPrice","Taxable","TaxCode","Note","ItemQuickBooksClassName","ItemDateScheduled","ShowItem","KitItem","RevisionLevel","CustomerPartNumber"]

#write first header row to CSV
#with open(fbcsv, "w", newline="") as csvfile:
    #wr = csv.writer(csvfile)
    #wr.writerow(header1)

#write second header row to CSV
#with open(fbcsv, "a", newline="") as csvfile:
    #wr = csv.writer(csvfile)
    #wr.writerow(header2)

#PRINT WORKING - .update does not work
with open(bccsv, newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        testdict.update("sonum": row['Order ID'])
        #print(row['Order ID'])
        #print(row['Billing Company'])
        #print(row['Customer Email'])
        #print(row['Customer Phone'])
        #print(row['Order Date'])
        #print(row['Ship Method'])
        #print(row['Billing Street 1'])
        #print(row['Billing Suburb'])
        #print(row['Billing State'])
        #print(row['Billing Zip'])
        #print(row['Billing Country'])
        #print(row['Billing Location Group'])
        #print(row['Billing koi_rep'])
        #print(row['Product Details'])

字符串

dgenwo3n

dgenwo3n1#

dictionary .update需要一个dictionary,你在testdict.update("sonum": row['Order ID'])中缺少花括号。

import csv

csv_file = """\
Order ID,Total
X123456,420.69
"""

testdict = {"ordertype": "SO"}

data = list(csv.DictReader(csv_file.splitlines()))

print(data) # [{'Order ID': 'X123456', 'Total': '420.69'}]

for row in data:
    testdict.update({"sonum": row["Order ID"]})
    # or
    testdict["total"] = row["Total"]

print(testdict) # {'ordertype': 'SO', 'sonum': 'X123456', 'total': '420.69'}

字符串

相关问题