smart way to read multiple variables from textfile in python
Question: I'm trying to load multiple vectors and matrices (for numpy) that are stored
in a single text file. The file looks like this:

    
    
    %VectorA
    1 2 3 4
    %MatrixA
    1 2 3
    4 5 6
    %VectorB
    3 4 5 6 7
    

The ideal solution would be to have a dictionary object like:

    
    
    {'VectorB': [3, 4, 5, 6, 7], 'VectorA': [1, 2, 3, 4], 'MatrixA':[[1, 2, 3],[4, 5, 6]]}
    

The order of the variables can be assumed as fixed. So, a list of the numpy
arrays in the order of appearance in the text file would also be okay.


Answer: 
    from StringIO import StringIO
    mytext='''%VectorA
    1 2 3 4
    %MatrixA
    1 2 3
    4 5 6
    %VectorB
    3 4 5 6 7'''
    
    myfile=StringIO(mytext)
    mydict={}
    for x in myfile.readlines():
        if x.startswith('%'):
            mydict.setdefault(x.strip('%').strip(),[])
            lastkey=x.strip('%').strip()
        else:
            mydict[lastkey].append([int(x1) for x1 in x.split(' ')])
    

above gives `mydict` as:

    
    
    {'MatrixA': [[1, 2, 3], [4, 5, 6]],
     'VectorA': [[1, 2, 3, 4]],
     'VectorB': [[3, 4, 5, 6, 7]]}
    

