Looks like a job for a database. If you're looking for compact solution (more compact than actual db, but probably less effective), look into what sqlite has to offer. For example this answer combined with this sqlite3 lib might solve your problem.