Search code examples
pythonpython-3.xcsvexport-to-csv

List of dictionaries using keys as headers & rows are the values of any data type


** I'm currently tasked with creating a CSV file from a list of dictionaries where the headers are the dict keys and the rows the dict values but values should be any data type.**

store_value = [{'Key': 649.0, 'Folder': '/ANZ/', 'End Date': 44907.0, 'Depends On': '', 'Start Date Constraint': '', 'Description': '', 'Resolution / Update': '', 'Comments': 'Comment', 'Staging Link': 'https://', 'Retailer URL': '', 'Item Number': ''}, {'Key': 651.0, 'Folder': '/ANZ/', 'End Date': 44917.0, 'Depends On': '', 'Start Date Constraint': '', 'Description': ' https:', 'Resolution / Update': '', 'Comments': 'Approved', 'Staging Link': '', 'Retailer URL': '', 'Item Number': ''}]
f = open("test.csv", "a")
f.write(','.join(list(store_value[0].keys())))  # write headers
f.write('\n')

for i in store_value:
    print(type(i))
    f.write(','.join(list(i.values())))  # write values
    f.write('\n')

f.close()

TypeError: sequence item 0: expected str instance, float found


Solution

  • You cannot join() float or int.

    Change this line:

    f.write(','.join(list(i.values())))
    

    ...to...

    f.write(','.join(map(str, i.values())))
    

    Having said that, your entire program can be simplified thus:

    import csv
    
    store_value = [
        {'Key': 649.0, 'Folder': '/ANZ/', 'End Date': 44907.0, 'Depends On': '', 'Start Date Constraint': '', 'Description': '', 'Resolution / Update': '', 'Comments': 'Comment', 'Staging Link': 'https://', 'Retailer URL': '', 'Item Number': ''},
        {'Key': 651.0, 'Folder': '/ANZ/', 'End Date': 44917.0, 'Depends On': '', 'Start Date Constraint': '', 'Description': ' https:', 'Resolution / Update': '', 'Comments': 'Approved', 'Staging Link': '', 'Retailer URL': '', 'Item Number': ''}
        ]
    
    with open('test.csv', 'w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=store_value[0])
        writer.writeheader()
        writer.writerows(store_value)