Home > Mobile >  Write Python Dictionary List Value into single CSV Cell?
Write Python Dictionary List Value into single CSV Cell?

Time:06-16

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)

CodePudding user response:

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'])

CodePudding user response:

You need to preprocess the rows before saving them into CSV.

so we using isinstance to check if the country_code2 is list or string

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'}
]

for row in rows:
    # check the country_code2 of every row if its and list
    if isinstance(row['country_code2'], list):
        # join the list to single string with ' ' seperating the values
        row['country_code2'] = ' '.join(row['country_code2'])

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