我有一个这样的字典列表:
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/