简体   繁体   English

在Python中生成具有多个值的CSV

[英]Generate CSV with multiple values in Python

{'id': '/en/45_2006', 'type': '/film/film', 'directed_by': ['Gary Lennon'], 'genre': ['Black comedy', 'Thriller', 'Psychological thriller', 'Indie film', 'Action Film', 'Crime Thriller', 'Crime Fiction', 'Drama'], 'name': '.45', 'initial_release_date': '2006-11-30'}

I have a list of such dictionaries from which I want to create a CSV file. 我有要从中创建CSV文件的此类词典的列表。

The following code seems to work fine. 以下代码似乎正常工作。 But when the dictionary has multiple values for a key (list) it writes the entire list as it is- 但是,当字典的某个键(列表)具有多个值时,它会按原样写入整个列表-

    keys = ['name', 'directed_by', 'genre', 'type', 'id', 'initial_release_date']
    with open('film.csv', 'w', newline='', encoding='utf8') as csvfile:
        dict_writer = csv.DictWriter(csvfile, keys)
        dict_writer.writeheader()
        dict_writer.writerows(filmlist)

How should I write the CSV files given the fact that certain keys have multiple values in a list and I want to write all of them. 鉴于某些键在列表中具有多个值,并且我想全部写入,因此我应该如何编写CSV文件。

This is an extension of jonrsharpes answer to take care of a special delimiter for your lists: 这是jonrsharpes答案的扩展,可以为您的列表使用特殊的定界符:

special_delim = '%'
for k, v in d.items():
     if isinstance(v, list):
        d[k] = special_delim.join(v)

You could convert all lists into strings first: 您可以先将所有列表转换为字符串:

for k, v in d.items():
    if isinstance(v, list):
        d[k] = str(v)

and use ast.literal_eval to retrieve the list when you read the csv file back in. 并在重新读回csv文件时使用ast.literal_eval检索列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM