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 list of such dictionaries want create csv file.
the following code seems work fine. when dictionary has multiple values key (list) writes entire list is-
keys = ['name', 'directed_by', 'genre', 'type', 'id', 'initial_release_date'] open('film.csv', 'w', newline='', encoding='utf8') csvfile: dict_writer = csv.dictwriter(csvfile, keys) dict_writer.writeheader() dict_writer.writerows(filmlist)
how should write csv files given fact keys have multiple values in list , want write of them.
this extension of jonrsharpes answer take care of special delimiter lists:
special_delim = '%' k, v in d.items(): if isinstance(v, list): d[k] = special_delim.join(v)
Comments
Post a Comment