DEV Community

Cover image for Build a Simple LEGO Inventory Tracker with Python and CSV
brickrecycler
brickrecycler

Posted on

Build a Simple LEGO Inventory Tracker with Python and CSV

A mixed LEGO collection can be hard to sort. Some pieces get used all the time, some belong to sets you want to keep together, and others have been sitting in a bin for years. A small Python script can help you decide what to keep and what to donate.

The trick is to track groups of pieces instead of counting every brick. One row can represent a bag, a bin, or a set.

Create the inventory

Save this as lego_inventory.csv:

group,container,decision
Loose bricks,Blue bin,keep
Space set,Clear bag,keep
Extra bricks,Small box,donate
Mixed pieces,Red bin,review
Enter fullscreen mode Exit fullscreen mode

The decision column tells the script what you plan to do with each group. Use review when you need more time to decide.

Build the Python script

Save this as lego_inventory.py in the same folder:

import csv
from pathlib import Path

inventory_path = Path(__file__).with_name("lego_inventory.csv")

with inventory_path.open(encoding="utf-8", newline="") as inventory:
    for row in csv.DictReader(inventory):
        if row["decision"].strip().lower() == "donate":
            print(f'{row["group"]} ({row["container"]})')
Enter fullscreen mode Exit fullscreen mode

Run it with python lego_inventory.py. With the sample file, it prints Extra bricks (Small box).

csv.DictReader uses the header row as the field names. That lets you write row["decision"] and still get the right value if you rearrange the columns.

Use the list to pack your donation

Once you’ve sorted your collection, run the script again to see which containers are ready to pack. If you’re in the U.S., Brick Recycler accepts LEGO donations, including loose bricks and incomplete sets. You can find packing and shipping instructions on its website.

Top comments (0)