I parsed some JSON data, creating bb_json
, and am trying to write CSV data based on it to csv_writer
. I have this code:
for product in bb_json['products']:
row = []
row.append(product['sku'])
if product['name']:
row.append(product['name'])
else:
row.append("")
if product['description']:
row.append(product['description'])
else:
row.append("none")
row.append(product['image'] + " ")
if product['manufacturer']:
row.append(product['manufacturer'])
else:
row.append("UNKNOWN")
row.append(product['upc'])
row.append(product['department'])
row.append(product['class'])
row.append(product['subclass'])
csv_writer.writerow(row)
But I get a KeyError
from the attempts to read data from product
, because many of these values are unpopulated. How can I fill in default values in the row
?
You can use your_dict.get(key, "default value")
instead of directly referencing a key.