In python 3, imaging we have this dictionary, where a cardholder can have unlimited numbers of cards. So if I want to covert the following dictionary into a csv, the number of columns will be unlimited and not very readable.
[{"cardholder_a":"SUSPENDED","card_a":"SUSPENDED","card_b":"SUSPENDED",
"card_c":"SUSPENDED"}]
Ideally the csv should have the following columns and rows:
'cardholder','cardholder_status','card','card_status'
'cardholder_a','SUSPENDED','card_a','SUSPENDED'
'cardholder_a','SUSPENDED','card_b','SUSPENDED'
'cardholder_a','SUSPENDED','card_c','SUSPENDED'
and I am trying to restructure the dictionary into
[{"cardholder_a":"SUSPENDED","card_a""SUSPENDED"},{"cardholder_a":"SUSPENDED","card_b""SUSPENDED"},
{"cardholder_a":"SUSPENDED","card_c""SUSPENDED"}]
so that I can easily convert the dictionary into the csv like the format shown above
import csv
csv_columns = ['cardholder','cardholder_status','card','card_status']
dict_data = [{"cardholder_a":"SUSPENDED","card_a""SUSPENDED"},{"cardholder_a":"SUSPENDED","card_b""SUSPENDED"},
{"cardholder_a":"SUSPENDED","card_c""SUSPENDED"}]
csv_file = "Names.csv"
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for data in dict_data:
writer.writerow(data)
except IOError:
print("I/O error")
Is there any easy way to convert the dictionaries above? Or any other better idea? Thank you!