chatgpt-4o-latest-20250326· OpenAI
LMArena Human Preference 140K
I have an array of dict in python. I want to save a csv file with the content. Please…
- User
I have an array of dict in python. I want to save a csv file with the content. Please write a function to do that
- Assistant
Certainly! Here's a simple Python function to save an array (list) of dictionaries to a CSV file:
import csv def save_dicts_to_csv(data, filename): """ Save a list of dictionaries to a CSV file. Parameters: - data (list of dict): The data to save. - filename (str): The path to the output CSV file. """ if not data: print("No data to write.") return # Get fieldnames from the first dictionary fieldnames = data[0].keys() with open(filename, mode='w', newline='', encoding='utf-8') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) # Write header writer.writeheader() # Write rows for row in data: writer.writerow(row) print(f"Data successfully written to {filename}")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.