python - 使用 python 将字典值写入 csv 中的单独列

标签 python csv dictionary

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

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

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

with open("text.csv", 'wb') as resultFile:
            wr = csv.writer(resultFile, dialect='excel')
            wr.writerow(['text', 'topics', 'categories'])

for d in list_of_dict:
    with open("text.csv", 'a') as f:
            w = csv.DictWriter(f, d.keys())
            w.writerow(d)

这会写入 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     |

如何做到这一点?谢谢!

最佳答案

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

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 文件:

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

关于python - 使用 python 将字典值写入 csv 中的单独列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46104479/

相关文章:

python - 如何在 Instagram API 上注册新客户

csv - LaTeX 和 pgf-pie 中 csv 文件的饼图

php - 使用 csv 文件更新 mysql 表。我需要调试器

iphone - 显示 Plist 词典中的随机单词 - 内存泄漏?

java - Java HashMap对象的并发访问

java - 为什么可以转换不同类型的 map ?

python - 根据条件Python对多行进行分组/求和

python - 使用 Twisted (python) 为 UDP 套接字设置超时

python - all() 和any() 总是按顺序短路吗?

node.js - 上传数据时暂停 Node csv-parser