Home > other >  How to create csv file with headers from list of dictionaries?
How to create csv file with headers from list of dictionaries?

Time:12-31

How can I create a csv file with the headings: name, job title, email address and salary. The rows should be filled with the appropriate values.

[{'Key': 'name', 'Value': 'bob'}, {'Key': 'job', 'Value': 'doctor'}, {'Key': 'email', 'Value': '[email protected]'}, {'Key': 'salary', 'Value': '10000'}]

Every solution I checked was structured differently and I'm not sure how to find this specific one.

https://blog.finxter.com/how-to-convert-a-python-dict-to-csv-with-header/

CodePudding user response:

This is a strange way to express data in python. Dictionaries have key value pairs and to have a dict that separates these is awkard at best. But you could assemble your own sane dict and use that to write the CSV. Your example only has 1 row of data,

import csv

data = [{'Key': 'name', 'Value': 'bob'}, {'Key': 'job', 'Value': 'doctor'}, {'Key': 'email', 'Value': '[email protected]'}, {'Key': 'salary', 'Value': '10000'}]

header = ('name', 'job', 'email', 'salary')

row = {kv_dict['Key']:kv_dict['Value'] for kv_dict in data}

with open("test.csv", "w", newline="") as outfile:
    writer = csv.DictWriter(outfile, fieldnames=header)
    writer.writeheader()
    writer.writerow(row)

CodePudding user response:

To create a csv file from a dictionary you can use csv module:

import csv
input_data = [{'Key': 'name', 'Value': 'bob'}, {'Key': 'job', 'Value': 'doctor'}, {'Key': 'email', 'Value': '[email protected]'}, {'Key': 'salary', 'Value': '10000'}]

with open('my_file.csv', 'w', newline="") as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(input_data[0].keys())
    for row in input_data:
        writer.writerow(row.values())

because it has multiple dictionaries, the code will loop to write each dictionary to as a separate row.

CodePudding user response:

import csv

mylist = [{'Key': 'name', 'Value': 'bob'}, {'Key': 'job', 'Value': 
'doctor'},
      {'Key': 'email', 'Value': '[email protected]'}, {'Key': 'salary', 
'Value': '10000'}]


    # Open the CSV file for writing
with open('new_file.csv', 'w', newline='') as csvfile:
    # Create a CSV writer
    writer = csv.DictWriter(csvfile, fieldnames=['Key', 'Value'])

    # Write the header row
    writer.writeheader()


    for items in mylist:
        writer.writerow(items)
  • Related