[英]How to save a dictionary to a csv where each key has a different row
import time
import csv
def file_reader():
product_location = {}
location = 0
with open('stockfile.csv', mode='r+') as f:
reader = csv.reader(f)
#next(reader) Can be included if I have headers to skip it
products = {rows[0]: (rows[1],rows[2],rows[3],rows[4],rows[5]) for rows in reader}
global products
with open('stockfile.csv', mode='r+') as f:
for line in f:
lines = line
print(lines)
product_location[line.split(',')[0]] = location
global product_location
f.close()
total=0
with open('stockfile.csv','r+') as f:
for line in f:
product_location[line.split(',')[0]] = location
location += len(line)
total = 0
while True:
file_reader()
GTIN = input("\nPlease input GTIN or press [ENTER] to quit:\n")
if GTIN == "":
break
if(GTIN not in products):
print("Sorry your code was invalid, try again:")
continue
row = products[GTIN]
description = row[0]
value = row[1]
stock = row[2]
additional_stock = row[3]
target_stock = row[4]
print("Updating stock levels back to target level")
stock = int(stock) + int(additional_stock)
print('GTIN: ', GTIN)
print('You have selected: ', description)
print('The price of this product is: ', value)
print('Stock: ', stock)
quantity = input("Please input the quantity required: ")
new_stock = int(stock) - int(quantity)
if int(quantity) > int(stock):
print("Sorry we don't have enough in stock please order again")
print("Please try a different product or a smaller quantity: ")
continue
else:
new_stock = int(stock) - int(quantity)
if int(new_stock) < int(target_stock):
answer = input("The stock is below target, if you would like to top up the product to the target stock level press [ENTER]")
if answer == "":
required = int(target_stock) - int(new_stock)
added_stock = input("This is the target stock: %s, you must enter a minimum of %s" % (target_stock,required))
stock= int(new_stock)+int(added_stock)
while int(stock) < int(target_stock):
print("Sorry input more please:")
continue
if int(stock) > int(target_stock):
additional_stock = 0
products[GTIN] = row[0],row[1],str(stock),str(additional_stock),row[4]
print(products[GTIN])
print(products)
writer = csv.writer(open('stockfile.csv','w',newline=''))
for key, row in products.items():
writer.writerow([key, value])
else:
additional_stock = int(target_stock) - int(new_stock)
#I need to do the same here and change the dictionary and then send it to the CSV
product_total = (int(quantity) * int(value))
total = total + product_total
print('Total of the order is £%s' % total)
我無法弄清楚如何使用這種格式將字典發送回 csv(這是它在開始時被調用時的格式,我想以相同的方式發回信息)。 這是 stockfile 的樣子:這是我希望字典被發送回以及打開時的格式。 請發布有效的代碼,並提前致謝。
我認為您的錯誤可能在您的“writer.writerow”行中,並且字典鍵/值之間可能存在一些混淆。
每個“writerow”都應該在每一行中寫入一個一維列表。 您在該行中定義為“行”的內容:
for key, row in products.items():
這實際上是字典key的值。 是的,該值的數據類型恰好是列表(或行),但該列表是字典鍵指向的值。
您的代碼不是試圖一次編寫一個列表行。 它實際上是在嘗試為可視化電子表格中的每一行寫入一個嵌套列表。 這是因為您的 Dictionary Key 的值本身就是一個 List 對象,它將一個列表放入另一個 writerow 列表中。
[ KeyName , ValueObject ]
由於我們的 ValueObject 是一個列表,我們在列表中有一個列表。
使用您的示例 stockfile,這是大多數 python 文件閱讀器解釋的電子表格中每一行的樣子:
[ KeyName , [ List, Of, Row, Values ] ]
這是具有 2 個維度的嵌套列表。 一行中只會寫入 2 個電子表格單元格。 解決這個問題的方法是確保“writer.writerow”一次只寫入一個一維列表。
實現此目的的一種簡單方法是將 2 個單獨的列表連接為該行的 1 個單個列表。
但是,由於您將值標記為“行”並將行項目之一標記為“值”,如果我們堅持您的上下文,我們應該能夠將該行值(這是一個列表)與鍵名連接起來與之相關。
for key, row in products.items():
writer.writerow ( [ key ] + row )
由於在這種情況下您的“行”值變量已經是一個列表,我們可以簡單地將字典鍵讀取為它自己的列表對象,以便在一個列表(和 1 行)中輕松連接。
那么 writerow 一次只寫入 1 個列表,並且該列表中的每個項目都放置在 csv 文件中按時間順序排列的單元格中。
根據您評論中的規范:
mydict = {'23456789': ('TV', '2000', '22', '0', '20'), '12345678': ('Fridge', '1000', '24', '0', '20'), '34567890': ('DVD', '10', '23', '0', '20')}
with open("out.csv", "w") as f:
for key in mydict:
f.write(key + "," + ",".join(mydict[key]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.