def read_file(fp): csv_fp = csv.reader(fp) D ={} next(csv_fp, None) for L in csv
ID: 3932906 • Letter: D
Question
def read_file(fp):
csv_fp = csv.reader(fp)
D ={}
next(csv_fp, None)
for L in csv_fp:
manufacturer = L[46]
year = L[63]
city_fuel = L[4]
highway_fuel = L[34]
if year != 2017:
if manufacturer in D:
D = {year: [[city_fuel], [highway_fuel]]]}
if year in D[manufacturer]:
D[manufacturer][year] = [[city_fuel], [highway_fuel]]
else:
D[manufacturer][year][0].append(city_fuel)
D[manufacturer][year][1].append(highway_fuel)
print (D)
return D
data = open_files()
in_files = read_file(data)
Everytime I run I get a KeyError: 'Honda' Honda is the first manufacturer listed (line 2) on the excel file im calling. I know KeyError is for when a key does not exist yet, but our prof gave us the if statement conditions: "if manufacturer in D:" and " if year in D[manufacturer]:" and said this is how you can get around the KeyError problem but it does not work. I have tried changing conditions and tried making it a dictionary with two keys instead of the current setup as a list of two lists but nothing works. Also we are skipping data from year 2017. I am new to dictionaries so any help would be great
Explanation / Answer
The below shows a snippet of definition of structure -
structure struct1 =
struct
val, exception and
fun definitions
end
The structure mapping can be defined as -
struct
exception NotFound;
val create = [];
fun lookup(key,[]) =
raise NotFound | lookup(key,
(key1,value1)::rest) =
if key = key1 //comparison of key
then value1
else lookup(key,rest);
fun insert(key,value,[]) =
[(key,value)]| insert(key,value,
(key1,value1)::rest) =
if key = key1
then (key,value)::rest
else (key1,value1)::
insert(key,value,rest);
end
// Above logic states the insertion and verification of the key and value using 'structure' without using files.
Members of the structure could be accessed as' Mapping.name'.
Thus Mapping.insert("herohonda","Manufacturer",[]);
char[] it = [("Herohonda","Manufacturer")] :
(Char * string) list
open Mapping;
exception NotFound
char create : 'a list
char insert : 'a (Manufacturer, "Herohonda")
//list -> ( * 'b) list
char lookup : 'a (Manufacturer, "Herohonda")
//list -> 'b
//Please confirm
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.