Turn raw comma-separated text into lists of dictionaries — the record structure behind every CSV file.
01
Learning objectives
Explain the CSV idea: one line per record, commas between fields, a header naming columns.
Split a line with split(',') and match each part to its field in the header.
Build a list of dictionaries from CSV-style lines, converting numeric fields with int() or float().
Explain why '88' and 88 behave differently and when conversion must happen.
Read a chosen field such as records[2]['marks'] from a built record list.
02
Lesson notes
Analysis begins with data shaped like a spreadsheet: each record is one entity (a student, a sale), each field one attribute (name, marks, city). The universal text format for this is CSV — comma-separated values: one line per record, fields between commas, and usually a header line naming the columns. Your board data questions are exactly this, and Python has no built-in spreadsheet — you build the records yourself.
The workhorse is split(): 'Ayesha,88,Lahore'.split(',') returns ['Ayesha', '88', 'Lahore']. The first line of the file, lines[0].split(','), yields the header — the field names in column order. Notice that every piece, including '88', arrives as a string of text. Beware: split() does not trim spaces, so 'Ayesha, 88' produces ' 88' with a leading space, which matters the moment you try to convert that text to a number.
Building records: skip the header, split each remaining line, and assemble a dictionary mapping field names to values. Critically, convert numeric fields — int(parts[1]) for marks — because split() only ever produces strings. The finished structure, a list of dictionaries, is chapter 6's nested data doing real work: from then on the file behaves like a table you can query in Python — loop over it, index it as records[0]['marks'], extend it, sort it.
Why does the conversion matter so much? Because '88' + 10 is a TypeError, and even where strings behave politely they sort wrongly: as strings, '9' comes after '88' because the character '9' beats '8'. Marks must be int or float before any mean, median or top-k logic can be trusted. Convert once, at load time, and everything downstream stays clean.
Board tip: exam papers hand you three or four CSV-style lines and ask for the record structure or a specific field. Write the header mapping first — column 0 is the name, column 1 the marks — then the loop. And when a value refuses to convert, chapter 9's toolkit applies: wrap int(parts[1]) in try/except and decide the policy, either skip that record or stop with a clear message.
03
Worked code examples
The header line names the columns
split(',') cuts the line at every comma into a list of strings — here the field names, in column order.