使用python将字典值作为单独的列写入csv

2024-04-30 03:15:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的字典列表:

list_of_dict = [
    {'text': '"Some text1"', 
     'topics': ['Availability', 'Waits'], 
     'categories': ['Scheduler']},
    {'text': 'Alot to improve'},
    {'text': 'More text '}
    ]

我将其写入csv文件,如下所示:

^{pr2}$

这将写入csv文件,如下所示:

text            |  topics                   | categories
Some text1      | ['Availability', 'Waits'] | ['Scheduler']
Alot to improve |
More text       |

但是,我希望对于每个类别和每个主题都应该有一个单独的列,那么如果某个主题存在于topics列表中,或者某个类别存在于categories列表中,则在该单元格中为文本的特定主题/类别写入True,否则写False。在

输出:

text             | Availability | Waits | Scheduler |
Some text1       | True         | True  | True      |
Alot to improve  | False        | False | False     |
More text        | False        | False | False     |

如何做到这一点?谢谢!在


Tags: totextfalsetrue列表moresomescheduler
1条回答
网友
1楼 · 发布于 2024-04-30 03:15:48

对于每个row来说,最简单的方法可能是从一个包含所有必需列值的默认字典开始设置为False,然后当读入list_of_dict中的每一行时,您可以发现它是否包含所需的键,并相应地更新您的row

import csv

list_of_dict = [
    {'text': '"Some text1"', 'topics': ['Availability', 'Waits'], 'categories': ['Scheduler']},
    {'text': 'Alot to improve'},
    {'text': 'More text '}]

all_topics = ["Availability", "Waits"]
all_categories = ["Scheduler"]
fieldnames = ["text"] + all_topics + all_categories

with open("text.csv", 'wb') as f_output:
    csv_output = csv.DictWriter(f_output, fieldnames=fieldnames, dialect='excel')
    csv_output.writeheader()

    for d in list_of_dict:
        # Build a default row
        row = {v:False for v in all_topics + all_categories}
        row['text'] = d['text'].strip('"')

        if 'topics' in d:
            row.update({topic:True for topic in d['topics']})
        if 'categories' in d:
            row.update({category:True for category in d['categories']})

        csv_output.writerow(row)

给您一个text.csv文件:

^{pr2}$

相关问题 更多 >