142k views
1 vote
Read_data Define a function named read_data with two parameters. The first parameter will be a csv reader object (e.g., the value returned when calling the function csv.reader) and the second parameter will be a list of strings representing the keys for this data. The list matches the order of data in the file, so the second parameter's first entry is the key to use for data in the file's first column, the second parameter's second entry is the key to use for data in the file's second column, and so on. The function's first parameter will be a csv reader object and not a string. This means you do not need the with..as nor create the csv reader in your function, but this will be done in the code calling your function. For example, to execute read_data using a file named "smallDataFileWithoutHeaders.csv" you would write the following code: with open("smallDataFileWithoutHeaders.csv") as f_in: csv_r = csv.reader(f_in) result = read_data(csv_r,['tow_date','tow_reason']) You would then want to include code to check that header had the expected value. The function should return a list of dictionaries. This list will contain a dictionary for each row read using the first parameter. The keys of these dictionaries will be the entries in the second parameter and the values will be the data read in from the file (you can assume there will be equal numbers list entries and columns).

For example, suppose the lines of the file being read by csv_r were:

2015-12-30,IL

2018-04-07,GA

then the call read_data(csv_r,['tow_date','tow_reason']) would need to return:

[{'tow_date': '2015-12-30', 'tow_reason': 'IL'},
{'tow_date': '2018-04-07', 'tow_reason': 'GA'}]

User Modika
by
4.0k points

1 Answer

3 votes

Answer:

Check the explanation

Step-by-step explanation:

Given below is the code for the question. PLEASE MAKE SURE INDENTATION IS EXACTLY AS SHOWN IN IMAGE.

import csv

def read_data(csv_r, keys):

data = []

for row in csv_r:

mydict = {}

for i in range(len(keys)):

mydict[keys[i]] = row[i]

data.append(mydict)

return data

SCREENSHOT:

Read_data Define a function named read_data with two parameters. The first parameter-example-1
User Karnivaurus
by
4.1k points