Python course Β· Module 4: Data, APIs and Databases

Data formats in the jungle

11 min read Β·
In this lesson9

Welcome to Module 4! Darwin here with a new chapter of our adventure.

So far you've learned Python from the basics to advanced OOP. Now it's time for data flow - how to store, exchange, and transport information between systems, just like animals communicate in the jungle!

In nature, animals convey information in various ways - birds through song, bees through dance, wolves through howling. In the programming world, we use data formats - standardized ways of recording information!

What are data formats?

A data format is a standardized way of organizing and recording information that can be read by different systems.

Safari Analogy: It's like a universal communication language - whether you're a biologist from Poland, a scientist from Japan, or a guide from Kenya, you all understand a table with lion population data!

  • JSON - JavaScript Object Notation - most popular in web APIs
  • CSV - Comma-Separated Values - simple, tabular
  • XML - eXtensible Markup Language - structural, extensive
  • YAML - YAML Ain't Markup Language - human-readable, configurations

JSON - JavaScript Object Notation

JSON is the most important data format in the web world - lightweight, readable, universal!

JSON Structure

{
  "species": "Panthera leo",
  "common_name": "Lion",
  "population": 120,
  "endangered": true,
  "habitats": ["savanna", "steppe"],
  "last_observation": {
    "date": "2024-01-15",
    "location": "Serengeti",
    "count": 12
  }
}

Data types in JSON:

  • "text" - string (always in quotes)
  • 123, 45.67 - number
  • true, false - boolean
  • null - no value
  • [1, 2, 3] - array (list)
  • {"key": "value"} - object (dictionary)

JSON in Python - the json module

Python has a built-in json module for working with this format:

import json

# Python β†’ JSON (serialization)
species_data = {
    "species": "Panthera leo",
    "common_name": "Lion",
    "population": 120,
    "endangered": True,
    "habitats": ["savanna", "steppe"],
    "last_observation": {
        "date": "2024-01-15",
        "location": "Serengeti",
        "count": 12
    }
}

# Convert to JSON string
json_string = json.dumps(species_data, indent=2)
print(json_string)
"""
{
  "species": "Panthera leo",
  "common_name": "Lion",
  "population": 120,
  "endangered": true,
  "habitats": [
    "savanna",
    "steppe"
  ],
  "last_observation": {
    "date": "2024-01-15",
    "location": "Serengeti",
    "count": 12
  }
}
"""

# JSON β†’ Python (deserialization)
json_text = '{"species": "Loxodonta africana", "population": 450}'
python_dict = json.loads(json_text)
print(python_dict["species"])  # "Loxodonta africana"

Reading and writing JSON files

import json

# Write to file
species_data = {
    "species": "Panthera leo",
    "population": 120,
    "observations": [
        {"date": "2024-01-15", "count": 12},
        {"date": "2024-01-20", "count": 8}
    ]
}

with open("species_data.json", "w", encoding="utf-8") as file:
    json.dump(species_data, file, indent=2, ensure_ascii=False)

# Read from file
with open("species_data.json", "r", encoding="utf-8") as file:
    loaded_data = json.load(file)
    print(loaded_data["species"])  # "Panthera leo"

Key difference:

  • json.dumps() / json.loads() - string (dumps = dump string)
  • json.dump() / json.load() - file

JSON and Python - type mapping

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
Truetrue
Falsefalse
Nonenull
import json

# Python β†’ JSON
python_data = {
    "name": "Darwin",
    "age": None,
    "active": True,
    "coordinates": (51.5, -0.1)  # Tuple β†’ array
}

json_str = json.dumps(python_data)
print(json_str)
# {"name": "Darwin", "age": null, "active": true, "coordinates": [51.5, -0.1]}

Serializing custom class objects

By default, JSON does not support custom class objects - you need a custom encoder:

import json
from datetime import datetime

class Species:
    def __init__(self, name, population, last_seen):
        self.name = name
        self.population = population
        self.last_seen = last_seen  # datetime object

    def to_dict(self):
        """Convert to dictionary"""
        return {
            "name": self.name,
            "population": self.population,
            "last_seen": self.last_seen.isoformat()  # datetime β†’ string
        }

    @classmethod
    def from_dict(cls, data):
        """Restore from dictionary"""
        return cls(
            name=data["name"],
            population=data["population"],
            last_seen=datetime.fromisoformat(data["last_seen"])
        )

# Serialization
lion = Species("Lion", 120, datetime.now())
json_data = json.dumps(lion.to_dict(), indent=2)
print(json_data)

# Deserialization
loaded_dict = json.loads(json_data)
lion_restored = Species.from_dict(loaded_dict)
print(lion_restored.name)  # "Lion"

CSV - Comma-Separated Values

CSV is a simple tabular format - perfect for spreadsheets and databases!

CSV Structure

species,common_name,population,habitat
Panthera leo,Lion,120,savanna
Loxodonta africana,Elephant,450,savanna
Python regius,Ball Python,85,jungle
Gorilla gorilla,Gorilla,230,forest

Characteristics:

  • First row = column headers
  • Subsequent rows = data
  • Separator: comma (sometimes semicolon, tab)

CSV in Python - the csv module

import csv

# WRITE CSV
species_data = [
    {"species": "Panthera leo", "common_name": "Lion", "population": 120},
    {"species": "Loxodonta africana", "common_name": "Elephant", "population": 450},
    {"species": "Python regius", "common_name": "Ball Python", "population": 85}
]

with open("species.csv", "w", newline="", encoding="utf-8") as file:
    fieldnames = ["species", "common_name", "population"]
    writer = csv.DictWriter(file, fieldnames=fieldnames)

    writer.writeheader()  # Write headers
    writer.writerows(species_data)  # Write all rows

# READ CSV
with open("species.csv", "r", encoding="utf-8") as file:
    reader = csv.DictReader(file)

    for row in reader:
        print(f"{row['common_name']}: {row['population']} individuals")
# Lion: 120 individuals
# Elephant: 450 individuals
# Ball Python: 85 individuals

CSV with lists (not dictionaries)

import csv

# Write lists
data = [
    ["species", "population", "endangered"],
    ["Panthera leo", 120, "True"],
    ["Loxodonta africana", 450, "True"]
]

with open("species_simple.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerows(data)

# Read lists
with open("species_simple.csv", "r", encoding="utf-8") as file:
    reader = csv.reader(file)
    headers = next(reader)  # First row = headers

    for row in reader:
        species, population, endangered = row
        print(f"{species}: {population}")

Different separators

import csv

# Separator: semicolon (popular in Europe)
with open("data_eu.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file, delimiter=";")
    writer.writerow(["species", "population"])
    writer.writerow(["Lion", "120"])

# Separator: tab
with open("data_tab.tsv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file, delimiter="\t")
    writer.writerow(["species", "population"])
    writer.writerow(["Lion", "120"])

XML - eXtensible Markup Language

XML is an extensive, structural format - used in enterprise, configurations, and data exchange between systems.

XML Structure

<?xml version="1.0" encoding="UTF-8"?>
<species_catalog>
    <species endangered="true">
        <scientific_name>Panthera leo</scientific_name>
        <common_name>Lion</common_name>
        <population>120</population>
        <habitats>
            <habitat>savanna</habitat>
            <habitat>steppe</habitat>
        </habitats>
        <observations>
            <observation>
                <date>2024-01-15</date>
                <location>Serengeti</location>
                <count>12</count>
            </observation>
        </observations>
    </species>
</species_catalog>

Characteristics:

  • Hierarchical tags: <tag>value</tag>
  • Attributes: <tag attribute="value">
  • Self-closing: <tag />
  • More verbose than JSON

XML in Python - the xml.etree.ElementTree module

import xml.etree.ElementTree as ET

# CREATING XML
root = ET.Element("species_catalog")

# Add a species
species = ET.SubElement(root, "species")
species.set("endangered", "true")  # Attribute

ET.SubElement(species, "scientific_name").text = "Panthera leo"
ET.SubElement(species, "common_name").text = "Lion"
ET.SubElement(species, "population").text = "120"

# Habitats
habitats = ET.SubElement(species, "habitats")
ET.SubElement(habitats, "habitat").text = "savanna"
ET.SubElement(habitats, "habitat").text = "steppe"

# Write to file
tree = ET.ElementTree(root)
ET.indent(tree, space="  ")  # Python 3.9+ - formatting
tree.write("species.xml", encoding="utf-8", xml_declaration=True)

# READING XML
tree = ET.parse("species.xml")
root = tree.getroot()

for species in root.findall("species"):
    name = species.find("common_name").text
    population = species.find("population").text
    endangered = species.get("endangered")  # Attribute

    print(f"{name}: {population} individuals (endangered: {endangered})")

    # Habitats
    habitats = species.find("habitats")
    for habitat in habitats.findall("habitat"):
        print(f"  - {habitat.text}")

YAML - YAML Ain't Markup Language

YAML is a human-readable format - popular in configurations (Docker, Kubernetes, CI/CD)!

YAML Structure

# Comment in YAML
species:
  scientific_name: Panthera leo
  common_name: Lion
  population: 120
  endangered: true
  habitats:
    - savanna
    - steppe
  last_observation:
    date: 2024-01-15
    location: Serengeti
    count: 12

# List of species
all_species:
  - name: Lion
    population: 120
  - name: Elephant
    population: 450
  - name: Ball Python
    population: 85

Characteristics:

  • Indentation determines hierarchy (like Python!)
  • - denotes a list element
  • key: value - key-value pairs
  • Very readable

YAML in Python - the PyYAML library

import yaml

# Installation: pip install pyyaml

# Python β†’ YAML
species_data = {
    "species": "Panthera leo",
    "common_name": "Lion",
    "population": 120,
    "endangered": True,
    "habitats": ["savanna", "steppe"],
    "last_observation": {
        "date": "2024-01-15",
        "location": "Serengeti",
        "count": 12
    }
}

# Convert to YAML string
yaml_string = yaml.dump(species_data, default_flow_style=False, allow_unicode=True)
print(yaml_string)

# YAML β†’ Python
yaml_text = """
species: Loxodonta africana
population: 450
endangered: true
"""

python_dict = yaml.safe_load(yaml_text)
print(python_dict["species"])  # "Loxodonta africana"

# File read/write
with open("config.yaml", "w", encoding="utf-8") as file:
    yaml.dump(species_data, file, default_flow_style=False, allow_unicode=True)

with open("config.yaml", "r", encoding="utf-8") as file:
    loaded_data = yaml.safe_load(file)

Safari example - complete data management system

import json
import csv
import xml.etree.ElementTree as ET
from datetime import datetime
from typing import List, Dict, Any

class Species:
    """Species class with export to various formats"""

    def __init__(self, scientific_name: str, common_name: str,
                 population: int, habitat: str, endangered: bool = False):
        self.scientific_name = scientific_name
        self.common_name = common_name
        self.population = population
        self.habitat = habitat
        self.endangered = endangered
        self.observations: List[Dict[str, Any]] = []

    def add_observation(self, date: str, location: str, count: int):
        """Add an observation"""
        self.observations.append({
            "date": date,
            "location": location,
            "count": count
        })

    # === EXPORT TO JSON ===

    def to_json_dict(self) -> dict:
        """Convert to dictionary for JSON"""
        return {
            "scientific_name": self.scientific_name,
            "common_name": self.common_name,
            "population": self.population,
            "habitat": self.habitat,
            "endangered": self.endangered,
            "observations": self.observations
        }

    @classmethod
    def from_json_dict(cls, data: dict) -> 'Species':
        """Restore from JSON dictionary"""
        species = cls(
            scientific_name=data["scientific_name"],
            common_name=data["common_name"],
            population=data["population"],
            habitat=data["habitat"],
            endangered=data.get("endangered", False)
        )
        species.observations = data.get("observations", [])
        return species

    # === EXPORT TO CSV ===

    def to_csv_row(self) -> dict:
        """Convert to CSV row (simplified - without observations)"""
        return {
            "scientific_name": self.scientific_name,
            "common_name": self.common_name,
            "population": self.population,
            "habitat": self.habitat,
            "endangered": "Yes" if self.endangered else "No"
        }

    # === EXPORT TO XML ===

    def to_xml_element(self) -> ET.Element:
        """Convert to XML element"""
        species_elem = ET.Element("species")
        species_elem.set("endangered", str(self.endangered).lower())

        ET.SubElement(species_elem, "scientific_name").text = self.scientific_name
        ET.SubElement(species_elem, "common_name").text = self.common_name
        ET.SubElement(species_elem, "population").text = str(self.population)
        ET.SubElement(species_elem, "habitat").text = self.habitat

        # Observations
        if self.observations:
            obs_elem = ET.SubElement(species_elem, "observations")
            for obs in self.observations:
                obs_item = ET.SubElement(obs_elem, "observation")
                ET.SubElement(obs_item, "date").text = obs["date"]
                ET.SubElement(obs_item, "location").text = obs["location"]
                ET.SubElement(obs_item, "count").text = str(obs["count"])

        return species_elem

    def __repr__(self) -> str:
        return f"Species('{self.common_name}', pop={self.population})"


class SpeciesDatabase:
    """Species database with export to various formats"""

    def __init__(self):
        self.species: List[Species] = []

    def add_species(self, species: Species):
        """Add a species"""
        self.species.append(species)

    # === JSON ===

    def export_json(self, filename: str):
        """Export to JSON"""
        data = {
            "export_date": datetime.now().isoformat(),
            "species_count": len(self.species),
            "species": [s.to_json_dict() for s in self.species]
        }

        with open(filename, "w", encoding="utf-8") as file:
            json.dump(data, file, indent=2, ensure_ascii=False)

        print(f"Exported {len(self.species)} species to {filename}")

    def import_json(self, filename: str):
        """Import from JSON"""
        with open(filename, "r", encoding="utf-8") as file:
            data = json.load(file)

        self.species.clear()
        for species_data in data["species"]:
            self.species.append(Species.from_json_dict(species_data))

        print(f"Imported {len(self.species)} species from {filename}")

    # === CSV ===

    def export_csv(self, filename: str):
        """Export to CSV"""
        if not self.species:
            print("No species to export")
            return

        fieldnames = ["scientific_name", "common_name", "population", "habitat", "endangered"]

        with open(filename, "w", newline="", encoding="utf-8") as file:
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            writer.writeheader()

            for species in self.species:
                writer.writerow(species.to_csv_row())

        print(f"Exported {len(self.species)} species to {filename}")

    def import_csv(self, filename: str):
        """Import from CSV"""
        self.species.clear()

        with open(filename, "r", encoding="utf-8") as file:
            reader = csv.DictReader(file)

            for row in reader:
                species = Species(
                    scientific_name=row["scientific_name"],
                    common_name=row["common_name"],
                    population=int(row["population"]),
                    habitat=row["habitat"],
                    endangered=(row["endangered"].lower() == "yes")
                )
                self.species.append(species)

        print(f"Imported {len(self.species)} species from {filename}")

    # === XML ===

    def export_xml(self, filename: str):
        """Export to XML"""
        root = ET.Element("species_database")
        root.set("export_date", datetime.now().isoformat())
        root.set("species_count", str(len(self.species)))

        for species in self.species:
            root.append(species.to_xml_element())

        tree = ET.ElementTree(root)
        ET.indent(tree, space="  ")
        tree.write(filename, encoding="utf-8", xml_declaration=True)

        print(f"Exported {len(self.species)} species to {filename}")

    def list_species(self):
        """Display all species"""
        print(f"\n=== SPECIES DATABASE ({len(self.species)}) ===")
        for i, species in enumerate(self.species, 1):
            status = "Warning: Endangered" if species.endangered else "Safe"
            print(f"{i}. {species.common_name} ({species.scientific_name})")
            print(f"   Population: {species.population}, Habitat: {species.habitat}, Status: {status}")


# === DEMONSTRATION ===

print("=== SAFARI DATA MANAGEMENT SYSTEM ===\n")

# Create database
db = SpeciesDatabase()

# Add species
lion = Species("Panthera leo", "Lion", 120, "savanna", endangered=True)
lion.add_observation("2024-01-15", "Serengeti", 12)
lion.add_observation("2024-01-20", "Masai Mara", 8)

elephant = Species("Loxodonta africana", "African Elephant", 450, "savanna", endangered=True)
elephant.add_observation("2024-01-16", "Amboseli", 35)

python_snake = Species("Python regius", "Ball Python", 85, "jungle", endangered=False)

db.add_species(lion)
db.add_species(elephant)
db.add_species(python_snake)

# Display data
db.list_species()

# EXPORT to various formats
print("\n=== EXPORT ===")
db.export_json("safari_data.json")
db.export_csv("safari_data.csv")
db.export_xml("safari_data.xml")

# IMPORT from JSON
print("\n=== IMPORT FROM JSON ===")
db2 = SpeciesDatabase()
db2.import_json("safari_data.json")
db2.list_species()

# IMPORT from CSV
print("\n=== IMPORT FROM CSV ===")
db3 = SpeciesDatabase()
db3.import_csv("safari_data.csv")
db3.list_species()

print("\nAll formats work correctly!")

Format comparison

FormatProsConsUsage
JSONLightweight, readable, universal in webNo commentsWeb APIs, configs, data exchange
CSVSimple, Excel-friendly, small sizeTables only, no hierarchyTabular data, spreadsheet export/import
XMLStructural, schema validationVerbose, more complexEnterprise, SOAP, legacy systems
YAMLVery readable, supports commentsSensitive to indentationConfigurations (Docker, K8s, CI/CD)

Summary

In this lesson you learned:

  • What data formats are and why we use them
  • JSON - json.dumps(), json.loads(), json.dump(), json.load()
  • CSV - csv.DictWriter, csv.DictReader, different separators
  • XML - xml.etree.ElementTree, creating and parsing
  • YAML - yaml.dump(), yaml.safe_load(), readability
  • Converting objects between formats
  • A practical data export/import system

Checkpoint

Before moving on:

  • You can read and write JSON
  • You understand the difference between dumps and dump
  • You can work with CSV (DictWriter/DictReader)
  • You know when to use which format
  • You can convert objects to dictionaries

Safari Analogy: Data formats are universal communication languages - just as biologists from different countries use Latin species names, programmers use JSON/CSV/XML to exchange data!

In the next lesson, Darwin will teach you HTTP and requests - how to fetch data from the internet and communicate with APIs!

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. JSON stands for:

  2. 2. Which function converts a Python dictionary to a JSON string?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Arrange the steps for reading JSON:

  • Code editor

    Save the dictionary animal = {'name': 'Tygrys', 'weight': 200} to the file 'animal.json'

  • Code editor

    Read the file 'animals.csv' and print all rows

  • Horizontal ordering

    Arrange: json.dumps(data, indent=2)

  • Click in order

    Click in order: with open('file.json', 'w') as f:

  • Vertical ordering

    Arrange the steps for writing JSON:

  1. QuestionJSON Format
  2. QuestionJSON in Python
  3. QuestionCSV Format
  4. Put in orderReading JSON from a File
  5. QuestionReading JSON from a File
  6. Coding taskWriting to JSON
  7. Coding taskReading CSV
  8. Put in orderJSON dumps
  9. Click in orderContext Manager
  10. Put in orderWriting JSON to a File

Useful articles