130k views
1 vote
Write a Python function that does the following:

Its name is write_csv
It takes a dictionary and a string file_name as arguments
It opens the file with file_name in write mode
It iterates over the dictionary to write lines to the opened .csv
Each key is the first element of the line, the values are lists that contain the other values in the line

User Ptmono
by
7.4k points

1 Answer

1 vote

Final answer:

The Python function 'write_csv' writes the contents of a dictionary to a CSV file, with each key-value pair translating to one line in the file. The function opens the file in write mode and uses csv.writer to format and write the data.

Step-by-step explanation:

The Python function you're looking to create is one that writes a CSV file from a dictionary. The function named write_csv will take two parameters: a dictionary, where each key holds a list as its value, and a file_name string, which indicates the name of the CSV file to be created. The function opens the file in write mode and writes each dictionary key and its corresponding values into the file, formatted as CSV.

Here's an example of how your Python function might look:

def write_csv(data_dict, filename):

with open (filename, 'w', newline='') as file:

writer = csv.writer(file)

for key, values in data_dict.items():

writer.writerow([key] + values)

This function uses the csv.writer object to write rows to the CSV file, where each row starts with the dictionary's key followed by its associated values from the list.

User Martin Delille
by
7.4k points