CSV from text, with DictWriter
CSV stores tables as lines of comma-separated text and JSON stores nested data as text with objects, arrays, numbers and strings. The csv and json modules read and write them, and they are the two formats you will meet most in data and AI work.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 7 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write parse_scores(text) that takes CSV text with the header name,score and returns a dict that maps each name to its score as an int. Use csv.DictReader and io.StringIO (which makes a string behave like a file). Test it with "name,score\nAsha,90\nBen,75\n".
Save {"a": [1, 2, 3], "b": {"c": None}} to a file data.json with indent=2. Read it back with json.load and print data["b"]. Hint: None becomes null in the file.
Write save_jsonl(path, records), which writes each record in a list as one JSON line, and load_jsonl(path), which reads them back into a list. Test that loading returns a list equal to the one you saved. Hint: use json.dumps per record and add "\n".
Explain it without notes
Why should you use the csv module instead of splitting lines on commas?
What is the difference between json.dump, json.dumps, json.load and json.loads?
Which Python values cannot be serialised by json.dumps by default, and what are your options?
What is JSON Lines and why is it popular for large datasets?
Expected output
skipping {'item': 'juice', 'price': 'x'}
total: 55
['item,price', 'tea,20', 'coffee,35']