import sqlite3


def create_abundance_dict(database, datasets):
    """Process the abundance table by dataset in order to create a dictionary
       data structure organized like this:
           transcript_ID -> dataset -> abundance in that dataset
    """
    abundance = {}    

    conn = sqlite3.connect(database)
    conn.row_factory = sqlite3.Row
    cursor = conn.cursor()

    for dataset in datasets:
        query = """ SELECT transcript_ID, count FROM abundance 
                    WHERE dataset = '%s' """ % dataset
        cursor.execute(query)

        for transcript in cursor.fetchall():
            transcript_ID = transcript["transcript_ID"]
            count = transcript["count"]  

            if transcript_ID in abundance:
                abundance[transcript_ID][dataset] = count
            else:
                abundance[transcript_ID] = {}
                abundance[transcript_ID][dataset] = count 

    conn.close()
    return abundance