JamesT JamesT - 6 months ago 20
Python Question

Dictionary of lists from tab delimited file

I'm attempting to load a tab delimited text file into a python program. It has the following format,

AAAAAA 1234 5678 90AB QQQQ JKL1
BBBBBB QWER TYUI ASDF QQQQ
CCCCCC ZXCV 1234 PPPP
...
ZZZZZZ 1111


In short, variable numbers of columns for each row, but always at least two and each column within a row is unique. The first column I would like to use as a key, and load the rest into a list with the key pointing to it. I tried looking into the csv module already as was suggested in other threads, but I've not quite found a way to make it work for me. So yeah, apologies if this should be more obvious, very much a newbie question.

Answer

simple str.split should work just fine for splitting the columns. Using that, you just need to read each row and split it into columns taking the first element as the key and the rest as the value:

with open(file) as fin:
     rows = ( line.split('\t') for line in fin )
     d = { row[0]:row[1:] for row in rows }