UMA MAHESWAR
UMA MAHESWAR

Reputation: 177

Exporting python list to csv

I have the below list called tes and I need to store it in csv format.

tes=[('branch=cse\\',{'name':['abc'],'sex':['male']}),('branch=ece\\',{'name':['def']})]

when the list have all the values,my code works good but if some value is missing in the list, I get KeyError. I have attached my code below. Can someone provide me with a better option ?

import csv
tes=[('branch=cse\\',{'name':['abc'],'sex':['male']}),('branch=ece\\',{'name':['def']})]
with open('check.csv','w') as csvfile:
    fieldnames = ['givenName','sex']
    writer=csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for i in tes:
        writer.writerow({'givenName': i[1]['name'], 'sex': i[1]['sex']})

Upvotes: 0

Views: 71

Answers (1)

furas
furas

Reputation: 142711

You can use i[1].get('sex', "default value"). If there is no key ['sex'] then it returns "default value" instead of KeyError

writer.writerow({'givenName': i[1].get('name', 'unknown'), 'sex': i[1].get('sex', 'male?')})

Upvotes: 1

Related Questions