【问题标题】:Write each value(list) in a dictionary of lists to a new row将列表字典中的每个值(列表)写入新行
【发布时间】:2017-10-03 21:57:12
【问题描述】:

我有一个包含 1 个键和多个列表值的字典。

{'A-03131': [['Component', 'P-011510', '5'], ['Component', 'P-011319', '1'], ['Component', 'A-03134', '1'], ['Component', 'P-009591', '1'], ['Component', 'P-011509', '1'], ['Component', 'P-011461', '1'], ['Component', 'P-011563', '1'], ['Component', 'A-03094', '2'], ['Component', 'A-03146', '1'], ['Component', 'P-011465', '4']]}

我正在尝试将每个列表值写入 CSV 中它自己的行。 我目前得到了这个:

    with open(file, 'w+') as outfile :
        w = csv.writer(outfile)
        w.writerows(sub_assembly.items())

但那是将完整的字典写入一行。

【问题讨论】:

    标签: csv dictionary python-3.5


    【解决方案1】:

    基本上在处理excel文件时,使用openpyxl包。 而不是直接编写遍历所有行并将每个列表插入一行。

    使用openpyxl,

    wb = openpyxl.Worksheet()

    ws = wb.active

    for value in d['A-03131']: cell(row = row,column = column).value = value

    wb.save('assembly.xlsx')

    这是一种更优雅的 excel 操作方式。

    【讨论】:

    • 我需要我的输出为 csv 格式,以便进一步处理。我想我已经找到了我的解决方案,一旦我开始工作就会发布
    • 我想你已经找到答案了。
    【解决方案2】:

    我发现 dict.values() 可以满足我的需求。

    filename = parent_item + '_bom.csv'
    file = os.path.join(OUTPATH, filename)
    header_row = ['Parent Item ', parent_item]
    with open(file, 'w+') as outfile:
        w = csv.writer(outfile, delimiter=',')
        w.writerow(header_row)
        for value in main_bom.values():
            w.writerows(value)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 2021-03-22
      • 2014-06-17
      • 1970-01-01
      • 2020-10-04
      • 2016-03-01
      相关资源
      最近更新 更多