Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write Python Dictionary List Value into single CSV Cell?

This is probably easy, but I’m not sure how to do it. This is purely an example, but for Algeria – how would I write both "DZ" and "DB" to a single row? The cell value is bracketed like a list, ['DZ', 'DB'] instead of something like DZ DB

import csv

# csv header
fieldnames = ['name', 'area', 'country_code2', 'country_code3']

# csv data
rows = [
    {'name': 'Albania',
     'area': 28748,
     'country_code2': 'AL',
     'country_code3': 'ALB'},
    {'name': 'Algeria',
     'area': 2381741,
     'country_code2': ['DZ', 'DB'],
     'country_code3': 'DZA'},
    {'name': 'American Samoa',
     'area': 199,
     'country_code2': 'AS',
     'country_code3': 'ASM'}
]

with open('countries.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(rows)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Convert a list of rows to a delimited string.

for row in rows:
    if isinstance(row['country_code2'], list):
        row['country_code2'] = ' '.join(row['country_code2'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading