CodeBlanks Logo Icon CodeBlanks

Summary - CSV and JSON

Combine csv.DictReader and json.dump to write a config file.

Summary - CSV and structured data

In this group you learned CSV reading/writing and structured data format operations. For CSV, csv.reader gives rows as lists and csv.DictReader as dicts. To write you use csv.writer with writerow/writerows.

For the structured data format on files use json.load/json.dump; for strings use json.loads/json.dumps. ensure_ascii=False handles Turkish characters; indent=2 gives readable indentation. Always include encoding="utf-8" when opening files.

Mini task: write structure to file

In the summary task you write structured data to a file and load it back. You keep a list inside a dict — a pattern common in real applications. You write with json.dump and read with json.load.

The task shows both the read-write loop and Turkish-character preservation together. The output is the count of items in the restored list, proving the data survived intact.

Practice Write and read a dict with a list

Start with import json. Define a dict with data = {"name": "Ayşe", "friends": ["Ali", "Veli"]}. Write it with with open("social.txt", "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2). Then read it back with with open("social.txt", "r", encoding="utf-8") as f: loaded = json.load(f). Print the friend count with print(len(loaded["friends"])).

Starter code

main.py
import json

# Define a data dict (with a list inside)
# Write to file, read back, print list length

Sample solution

main.py
import json

# Define a data dict (with a list inside)
data = {"name": "Ayşe", "friends": ["Ali", "Veli"]}
# Write to file, read back, print list length
with open("social.txt", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)
with open("social.txt", "r", encoding="utf-8") as f:
    loaded = json.load(f)
    print(len(loaded["friends"]))

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method reads CSV as dictionaries?

  • csv.writer
  • csv.reader
  • csv.DictReader Correct answer
  • csv.DictWriter

Explanation: Csv.DictReader. This method reads rows as dictionaries.

2 json.dump writes to a file

Question
import json
data = {"name": "Veli"}
with open("v.txt", "w", encoding="utf-8") as f:
    json.____(data, f, ensure_ascii=False)
Answer
import json
data = {"name": "Veli"}
with open("v.txt", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False)

Explanation: json.dump writes to a file.

3 Match the module uses

Term Meaning
csv.reader CSV row as list
csv.DictReader CSV row as dict
json.load Reading from a file
json.dumps Writing to a string

All lessons in Intermediate