''' DS2000 Fall 2024 Starter code for class on 11/1/24 There's a little starter code in here, and then we're going to add in two more functions: 1. row_to_dct parameters - two lists of strings, row & keys, same length (the first list is a row from the csv file, the second is a list of keys which are the header of the csv file) returns - a dictionary of strings where key comes from second list, value comes from first list does - creates an empty dictionary, then iterates by position over list of keys. Every keys[i] becomes a key in the dictionary, with value row[i] 2. count_greater parameters - two lists of dictionaries, string for column name, int for threshold returns - an int, the number of values in the given column > the given threshold does - iterates over the list of dictionaries. In each dictionary, looks in the given column (col name will be the key). If the value is > given threshold, increment the count ''' import csv FILENAME = "1920-voter_registration.csv" def csv_to_lst_of_dct(filename): ''' parameter: filename, a string returns: list of dictionaries (all key/value pairs are strings) does: creates a list of dictionaries where each dictionary represents one row from the CSV file. Dictionary keys are from the header of the csv file, and dictionary values are from the rows. ''' data = [] with open(filename, 'r') as infile: csvfile = csv.reader(infile) keys = next(csvfile) for row in csvfile: dct = row_to_dct(row, keys) data.append(dct) return data def row_to_dct(row, keys): ''' params: 2 lists of strings (one row from csv file, one list of keys) returns: a dictionary where keys come from one list, and values from the other does: turns lists into key/value pairs ''' dct = {} for i in range(len(row)): k = keys[i] v = row[i] dct[k] = v return dct def count_greater(lst_of_dct, col_name, mn_val): ''' params: list of dictionaries, col name (string), mn_value (number) return: an int does: count the number of values in teh given column greater than the minimum value ''' count = 0 for dct in lst_of_dct: val = int(dct[col_name]) if val > mn_val: count += 1 return count def main(): # step one: gather data by turning CSV file into # list of dictionaries lst_of_dct = csv_to_lst_of_dct(FILENAME) # step one cont'd: gather data by prompting user # for minimum age to look for in voter list age = int(input("What age to look for?\n")) # step two: computation, count the number of women # registered to vote who were over the given age count = count_greater(lst_of_dct, "Age", age) # step three: communicate by printing the count print(count, "women over age", age, "registered!") main()