从字典列表写入CSV文件,每个键有多个值?

时间:2016-06-15 17:22:14

标签: python python-2.7 csv

results = [
            {"Name" : "Name1", "Issues" : ["issue1", "issue2",    "issue3"]},
            {"Name" : "Name2", "Issues" : "issue1"},
            {"Name" : "Name3", "Issues" : ["issue2", "issue4"]},
            {"Name" : "Name4", "Issues" : "issue4"}
            ]

这是我的示例字典,下面是我用来将其写入CSV文件的代码。

writer = csv.DictWriter(filename, results[0].keys(), dialect ="excel",   delimiter=',')
writer.writeheader()
for result in results:
    writer.writerow(result)

这是当前的输出

Name,Issues
Name1,['issue1', 'issue2', 'issue3']
Name2,issue1
Name3,['issue2', 'issue4']
Name4,issue4

如您所见,有时候每个名称会出现多个问题。我希望他们用不同的分隔符将它们分开。 例如

Name,Issues
Name1,issue1 issue2 issue3
Name2,issue1
Name3,issue2 issue4
Name4,issue4

我如何实现这一目标?我特别想用dict writer模块回答。

1 个答案:

答案 0 :(得分:1)

这是一种方式:

for result in results:
    writer.writerow({k:' '.join(v) if isinstance(v, list) else v
                    for k,v in result.items()})

.writerow()需要一个字典,其键和值是字符串。由于您的字典值有时是列表,我们需要一些代码将列表转换为字符串。

以下是我使用的技术的解释:

' '.join(v)   # Converts the list (v) to a space-separated string

isinstance(v, list) # Decides if (v) is a list or not

' '.join(v) if isinstance(v, list) else v 
              # Evaluates to either v (if v is a string) 
              # or a string (if v is a list)

{k:...for k,v in result.items()} # Creates the new dictionary, where
                                 # all values are strings

<小时/>

修改

根据以下评论中描述的新要求,我可能会这样做:

with open('output.txt', 'w') as output_file:
    writer = csv.writer(output_file,
                        dialect ="excel",
                        delimiter=',')
    writer.writerow(["Name", "Issues"])
    for result in results:
        row = []
        row.append(result["Name"])
        if isinstance(result["Issues"], list):
            row.extend(result["Issues"])
        else:
            row.append(result["Issues"])
        writer.writerow(row)

请注意,我们已从csv.DictWriter更改为csv.writer,以便我们可以更好地控制列。