79.4k views
0 votes
Write a Python function that does the following:

1. Its name is write_csv
2. It takes a dictionary and a string file_name as arguments
3. It opens the file with file_name in write mode
4. It iterates over the dictionary to write lines to the opened . csv
5. Each key is the first element of the line, the values are lists that contain the other values in the line
Test cases:
my_data ={ "Peter": [1000], "Joan": [50500], "Mary": [2400] }
write_csv(my_data, "stipends.csv")
This is what stipends.csv should contain:
Peter, 1000
Joan, 50500
Mary, 2400
my_data = \{"Country": ["United States", "Brazil", "Mexico", "Canada"], "Population (in mil)": [331.00,212.56,128.93,37.74]}
write_csv(my_data, "population.csv")
This is what population.csv should contain:
Country, United States, Brazil, Mexico, Canada
Population (in mil), 331. 0,212.56,128.93,37.74

1 Answer

3 votes

Final answer:

The function write_csv takes a dictionary and a file_name as arguments, writing a .csv file where each line corresponds to one key-value pair from the dictionary, with the key as the first element of the line and the list of values as subsequent elements.

Step-by-step explanation:

The student has requested the creation of a Python function called write_csv that generates a .csv file from a dictionary. Below is the Python code for the described function:

def write_csv(data_dict, file_name):
with open(file_name, 'w', newline='') as csv_file:
for key, values in data_dict.items():
csv_file.write(f'{key}, ' + ', '.join(map(str, values)) + '\\')

This function takes a dictionary where each key has a list of values, and a string file_name, and creates a .csv file with each key-value pair on a separate line. When calling write_csv(my_data, "stipends.csv") with the provided dictionary, the generated stipends.csv file would contain lines like "Peter, 1000" and so forth. Similarly, write_csv(my_data, "population.csv") will produce a population.csv with the appropriate data layout.

User Meh
by
7.8k points