Skip to content
KALANBLON
Show contents

Chapter 4 of 6 · 20 min

CSV and JSON: exchanging data

By the end of this chapter, you'll be able to

  • Read and write a CSV file with the csv module
  • Convert the values read, which are always text
  • Turn lists and dictionaries into JSON, and back
  • Choose between CSV and JSON depending on the shape of the data

CSV: tables as text

A CSV file (Comma-Separated Values) is a table: one line per record, columns separated by commas, and often a first line of headers. Every spreadsheet can open and export it.

Python's csv module takes care of the tedious details, such as a comma inside a value. csv.writer writes rows, csv.DictReader reads each row as a dictionary whose keys are the headers:

import csv

sales = [
    ["product", "quantity", "price"],
    ["mango", "12", "0.5"],
    ["pineapple", "3", "2.0"],
    ["mango", "5", "0.5"],
]
with open("sales.csv", "w", newline="", encoding="utf-8") as f:
    csv.writer(f).writerows(sales)

totals = {}
with open("sales.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        amount = int(row["quantity"]) * float(row["price"])
        totals[row["product"]] = totals.get(row["product"], 0) + amount
print(totals)
{'mango': 8.5, 'pineapple': 6.0}

newline="" lets the csv module handle line endings itself: it's the recommended way to open a CSV file.

Last row: 5 more mangoes, that is 2.5. The mangoes' total goes up to 8.5.

Step 6 of 6
Text description of the animation
  1. DictReader first reads the header line: product, quantity, price. They'll become the keys.
  2. First data row. Careful: all the values are strings, even '12'.
  3. We convert before computing: 12 × 0.5 = 6.0.
  4. We add the amount to the product's total.
  5. Next row: 3 pineapples at 2.0.
  6. Last row: 5 more mangoes, that is 2.5. The mangoes' total goes up to 8.5.

JSON: structured data

JSON (JavaScript Object Notation) represents nested data: objects (like dictionaries), lists, numbers, texts, true, false and null. It's the format of most web APIs and configuration files.

import json

profile = {"name": "Aïcha", "languages": ["French", "Wolof"], "level": 2, "active": True}
text = json.dumps(profile, ensure_ascii=False)
print(text)

copy = json.loads(text)
print(copy["languages"][1], type(copy["level"]).__name__)

with open("profile.json", "w", encoding="utf-8") as f:
    json.dump(profile, f, ensure_ascii=False, indent=2)
with open("profile.json", encoding="utf-8") as f:
    print(json.load(f) == profile)
{"name": "Aïcha", "languages": ["French", "Wolof"], "level": 2, "active": true}
Wolof int
True
  • dumps (dump string) turns a Python value into JSON text; loads does the reverse.
  • dump and load, without the "s", do the same directly with a file.
  • ensure_ascii=False keeps accents readable (otherwise ï becomes ï); indent=2 lays the file out on several lines, easier for a human to read.
  • Unlike CSV, JSON keeps the types: 2 comes back as an integer, True as a boolean.

Which one to choose? CSV for a simple table that someone will open in a spreadsheet. JSON for nested data (lists inside dictionaries) or to exchange it with another application.

Your turn

Worked exercise

Worked exercise: from CSV to JSON

A file contacts.csv has the columns name and city. Write a function by_city(csv_file, json_file) that groups the names by city in a dictionary {city: [names]}, saves it as readable JSON (accents kept, indentation of 2) and returns this dictionary.

Hint 1
Read the CSV with csv.DictReader: contact["city"] and contact["name"] are directly available.
Hint 2
cities.setdefault(city, []) returns the city's list, creating it empty if it doesn't exist yet: you can call .append(name) directly on it.
Show the solution and common mistakes
import csv
import json

with open("contacts.csv", "w", newline="", encoding="utf-8") as f:
    f.write("name,city\nIbrahim,Bamako\nLucía,Quito\nMoussa,Bamako\n")

def by_city(csv_file, json_file):
    cities = {}
    with open(csv_file, newline="", encoding="utf-8") as f:
        for contact in csv.DictReader(f):
            cities.setdefault(contact["city"], []).append(contact["name"])
    with open(json_file, "w", encoding="utf-8") as f:
        json.dump(cities, f, ensure_ascii=False, indent=2)
    return cities

print(by_city("contacts.csv", "cities.json"))
with open("cities.json", encoding="utf-8") as f:
    print(f.read())
{'Bamako': ['Ibrahim', 'Moussa'], 'Quito': ['Lucía']}
{
  "Bamako": [
    "Ibrahim",
    "Moussa"
  ],
  "Quito": [
    "Lucía"
  ]
}

Common mistakes:

  • Writing cities[contact["city"]].append(...) without creating the list first: KeyError from the very first city.
  • Splitting lines by hand with split(","): it breaks as soon as a value contains a comma ("Dakar, Senegal"). The csv module handles this case.

Summary

  1. 1CSV stores a table: csv.writer writes, csv.DictReader reads dictionaries.
  2. 2Everything read from a CSV is text: convert with int() or float().
  3. 3JSON stores nested data and keeps the types: json.dump/json.load for files.
  4. 4ensure_ascii=False keeps accents, indent=2 makes the file readable.
  5. 5CSV for a spreadsheet, JSON for structured data or another application.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.