如何将字典保存到csv,其中每个键具有不同的行

时间:2016-03-22 15:18:46

标签: python csv python-3.x dictionary export-to-csv

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的样子:This is the format I want the dictionary to be sent back in as well as when it is opened。 请发布代码,并提前付款。

2 个答案:

答案 0 :(得分:0)

我认为您的错误可能在您的“writer.writerow”行中,并且可能在字典键/值之间存在一些混淆。

每个“作家”应该在每一行写一个单维列表。您在行中定义为“行”的内容:

    for key, row in products.items():

这实际上是字典。是的,该值的数据类型恰好是列表(或行),但该列表是字典指向的

您的代码不是一次尝试写一个列表行。它实际上是尝试将嵌套列表写入可视电子表格中的每一行。这是因为Dictionary Key的值是一个List对象,它将一个列表放在另一个writerow列表中。

    [ KeyName  ,  ValueObject  ]

由于我们的ValueObject是一个List,因此我们在列表中有一个列表。

使用您的样本库存文件,这是大多数python文件读取器解释的电子表格中每行的样子:

    [ KeyName  ,  [ List, Of, Row, Values ] ]

这是具有2个维度的嵌套列表。只有2个电子表格单元格会写入一行。解决这个问题的方法是确保“writer.writerow”一次只写一个1维列表。

实现此目的的一种简单方法是将2个单独的列表连接到该行的1个单个列表中。

但是,由于您将值标记为“行”并将其中一个行标记为“值”,如果我们坚持您的上下文,我们应该能够连接该行值(这是一个列表)与之关联的密钥名称。

    for key, row in products.items():
        writer.writerow (  [ key ]  +  row  )

由于在这种情况下你的“行”值变量已经是一个列表,我们可以简单地将字典键作为自己的列表对象读取,以便在一个列表(和1行)中轻松连接。

因此,编者只能一次编写1个列表,该列表中的每个项目都放在csv文件中自己的时间单元格中。

答案 1 :(得分:0)

根据您评论中的说明:

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]))