Programming from zero

Parse a CSV server inventory into a list of dictionaries

mediumReading and writing files

Problem statement

A CSV file is plain text where each line is a row and commas separate the columns. The first line is usually the header, the names of the columns.

To turn it into something useful:

  • Read the header and split it on commas. These become the keys.
  • For every other line, split on commas. These become the values.
  • Pair each key with its value in a dictionary. One dictionary per row.

This page uses plain splitting. It works for simple files like this one. It would break if a value itself contained a comma.

Common mistake: forgetting that each line ends with a line break.

TEXT
Wrong:
values = line.split(",")
Last value is "up\n", not "up"

In Python, line.strip() removes the line break before splitting. Java's readLine() and C++'s getline already remove it.

Your task: servers.csv has a header and three rows (the code below creates it). Write parse_inventory(path) that returns a list of dictionaries, one per server. Then print each server as <hostname> -> <ip> (<status>).

Expected output

◈ DIAGRAM
web-01 -> 10.0.0.1 (up)
web-02 -> 10.0.0.2 (down)
db-01 -> 10.0.0.3 (up)

Approach

Split the header once, then build one dictionary per remaining line:

  • Python: line.strip().split(",") gives a list. A loop over range(len(header)) pairs each key with its value.
  • Java: line.split(",") gives an array. Each row is a LinkedHashMap<String, String>, and all rows go into an ArrayList.
  • C++: there is no built-in split, so a small split helper reads pieces up to each comma with std::getline. Each row is a std::map<std::string, std::string>.

The setup lines only create the sample servers.csv.

# Setup: create a small sample CSV
with open("servers.csv", "w") as f:
    f.write("hostname,ip,status\nweb-01,10.0.0.1,up\nweb-02,10.0.0.2,down\ndb-01,10.0.0.3,up\n")


def parse_inventory(path):
    records = []
    with open(path) as f:
        header = f.readline().strip().split(",")
        for line in f:
            values = line.strip().split(",")
            record = {}
            for i in range(len(header)):
                record[header[i]] = values[i]
            records.append(record)
    return records


for server in parse_inventory("servers.csv"):
    print(f"{server['hostname']} -> {server['ip']} ({server['status']})")