如何将包含列表的字典转换为特定的行?

时间:2017-05-04 07:11:34

标签: python dictionary transformation export-to-csv python-2.6

我有Python脚本:

for row in file:
    ....
    ....
    ....
    whole_calendar = {}
    whole_calendar['ID'] = id
    whole_calendar['OPEN'] = open_days
    whole_calendar['CLOSED'] = closed_days
    whole_calendar['CHECKED'] = checked_days
    print(whole_calendar)

生成(迭代)许多类似的字典行:

{'ID': ['133528'], 'OPEN': ['1/1/2016', '2/1/2016', '3/1/2016', '4/1/2016'], 'CLOSED': ['5/1/2016'], 'CHECKED': ['1/7/2016']}

{'ID': ['176987'], 'OPEN': ['3/6/2016', 4/6/2016'], 'CLOSED': [], 'CHECKED': ['1/7/2016',2/7/2016]}

{'ID': ['347697'], 'OPEN': ['1/2/2016'], 'CLOSED': ['1/3/2016'], 'CHECKED': []}

我需要的是将这些词典(行)以此表格的形式写入CSV文件 - >

133528,'OPEN','1/1/2016'
133528,'OPEN','2/1/2016'
133528,'OPEN','3/1/2016'
133528,'OPEN','4/1/2016'
133528,'CLOSED','5/1/2016'
133528,'CHECKED','1/7/2016'
176987,'OPEN','3/6/2016'
176987,'OPEN','4/6/2016'
176987,'CHECKED','1/7/2016'
176987,'CHECKED','2/7/2016'
347697,'OPEN','1/2/2016'
347697,'CLOSED','1/3/2016'

我需要在Python 2.6中使用内置的库(没有Pandas)

我尝试了一些转换+使用csv.writerow,但我不能这样做。 你能帮帮我吗?

2 个答案:

答案 0 :(得分:0)

您正在使用中间字典步骤使事情变得复杂。您可以在读取旧文件中的行时编写新文件。

import csv

with open('new_format.csv', 'w') as csvfile:
    fieldnames = ['id', 'status', 'date']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    for row in file:
        ....
        ....
        ....
        [writer.writerow({'id': id, 'status': 'OPEN', 'date': d}) for d in open_days]
        [writer.writerow({'id': id, 'status': 'CLOSED', 'date': d}) for d in closed_days]
        [writer.writerow({'id': id, 'status': 'CHECKED', 'date': d}) for d in checked_days]

答案 1 :(得分:0)

安德鲁的回答并非100%适用于我,但在我做了一些小改动之后:

import csv

with open('new_format.csv', 'w') as csvfile:
    fieldnames = ['id', 'status', 'date']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    for row in file:
        ....
        ....
        ....
        writer.writerows({'id': id, 'status': 'OPEN', 'date': d} for d in open_days)
        writer.writerows({'id': id, 'status': 'CLOSED', 'date': d} for d in closed_days)
        writer.writerows({'id': id, 'status': 'CHECKED', 'date': d} for d in checked_days)

它确实看起来几乎是正确的(我不知道为什么我会得到空行):

    ...
    8: 4882410,CLOSED,2016-11-09
    9:
    10: 4882410,CLOSED,2016-11-10
    11:
    12: 4882410,CLOSED,2016-11-11
    ...