简体   繁体   English

如何将字典保存到每个键都有不同行的 csv

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

I am unable to work out how to send the dictionary back to the csv with this format (this is the format it is in when it has been called upon at the start and I want to send the information back in the same way).我无法弄清楚如何使用这种格式将字典发送回 csv(这是它在开始时被调用时的格式,我想以相同的方式发回信息)。 This is what the stockfile looks like: This is the format I want the dictionary to be sent back in as well as when it is opened .这是 stockfile 的样子:这是我希望字典被发送回以及打开时的格式 Please post the code as well which works and thanks in advance.请发布有效的代码,并提前致谢。

I think your error may be in your "writer.writerow" line and possibly some confusion between dictionary keys/values.我认为您的错误可能在您的“writer.writerow”行中,并且字典键/值之间可能存在一些混淆。

Every "writerow" should be writing a single 1-Dimensional List in every row.每个“writerow”都应该在每一行中写入一个一维列表。 What you define as a "row" in the line :您在该行中定义为“行”的内容:

    for key, row in products.items():

That is actually the value of the dictionary key .这实际上是字典key Yes, the data type of that value happens to be a list ( or a row ), but that list is the value that the dictionary key is pointing to.是的,该值的数据类型恰好是列表(或行),但该列表是字典指向的

Your code is not trying to write one single list row at a time.您的代码不是试图一次编写一个列表行。 It is actually trying to write a Nested List to each Row in your visual spreadsheet.它实际上是在尝试为可视化电子表格中的每一行写入一个嵌套列表。 This is because the Value of your Dictionary Key is a List object in-itself which puts a list inside another writerow list.这是因为您的 Dictionary Key 的值本身就是一个 List 对象,它将一个列表放入另一个 writerow 列表中。

    [ KeyName  ,  ValueObject  ]

Since our ValueObject is a List, we have a list inside a list.由于我们的 ValueObject 是一个列表,我们在列表中有一个列表。

Using your sample stockfile, this is how each row would look like in the spreadsheet as interpreted by most python file readers :使用您的示例 stockfile,这是大多数 python 文件阅读器解释的电子表格中每一行的样子:

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

That's Nested List with 2 Dimensions.这是具有 2 个维度的嵌套列表。 Only 2 Spreadsheet Cells would be written to in one row.一行中只会写入 2 个电子表格单元格。 The way to fix this is to make sure that "writer.writerow" is only writing a single 1-Dimensional List at a time.解决这个问题的方法是确保“writer.writerow”一次只写入一个一维列表。

An easy way to accomplish this is to concatenate 2 separate lists into 1 single list for the row.实现此目的的一种简单方法是将 2 个单独的列表连接为该行的 1 个单个列表。

However, since you are labeling the value as a "row" and one of the row items as "value", if we stick to your context, we should be able to concatenate that row value ( which is a list ) with the key name associated with it.但是,由于您将值标记为“行”并将行项目之一标记为“值”,如果我们坚持您的上下文,我们应该能够将该行值(这是一个列表)与键名连接起来与之相关。

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

Since your "row" value variable in this case is already a list, we can simply read the dictionary key as its own list object to concatenate easily in one list ( and 1 line).由于在这种情况下您的“行”值变量已经是一个列表,我们可以简单地将字典键读取为它自己的列表对象,以便在一个列表(和 1 行)中轻松连接。

So then writerow is only writing 1 list at a time and each item in that list is placed in its own chronological cell in your csv file.那么 writerow 一次只写入 1 个列表,并且该列表中的每个项目都放置在 csv 文件中按时间顺序排列的单元格中。

According to the specification in your comment:根据您评论中的规范:

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.

相关问题 如何将字典密钥保存到同一行的CSV文件中 - How to save dictionary key into csv file on the same row python字典到csv,其中每个键在单独的行中以及单独的列中的值 - python dictionary to csv where each key is in seperate row and value in separate columns 当行内容是相关键的键值(每列的标题)时,如何用python在csv中编写嵌套字典? - How to write nested dictionary in csv with python when the row contents are key values of related key (the header of each column)? 如何将多键字典转换为 pandas dataframe,其中每个键和值都有自己的列? - How to convert a multi-key dictionary to a pandas dataframe, where each key and value has its own column? 如何逐行构建数据框,其中每一行来自不同的 csv? - How to build a dataframe row by row, where each row comes from a different csv? 如何将 CSV 读入 Python 字典,其中每个键的值都是字典列表? - How can I read a CSV into a Python dictionary, where each key's value is a list of dicts? 如何从csv文件中保存每一行 - How to save each row from csv file 如何读取具有分组数据且每组具有不同列的 CSV? - How to read a CSV which has grouped data where each group has different columns? 创建一个 Python 字典,其中每个键都有一个列表作为值 - create a Python dictionary where for each key has a list as the value 如何将Python中的数据列表转换为每个项目都有一个键的字典 - How to convert a list of data in Python to a Dictionary where each item has a key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM