You can use pandas to load df, then build a new df as desired, and then call to_dict :
In [99]: t="""abc -0.123 0.6524 0.325 foo -0.9808 0.874 -0.2341 bar 0.23123 -0.123124 -0.1232""" df = pd.read_csv(io.StringIO(t), sep='\s+', header=None) df = pd.DataFrame(columns = df[0], data = df.ix[:,1:].values) df.to_dict() Out[99]: {'abc': {0: -0.12300000000000001, 1: -0.98080000000000001, 2: 0.23123000000000002}, 'bar': {0: 0.32500000000000001, 1: -0.2341, 2: -0.1232}, 'foo': {0: 0.65239999999999998, 1: 0.87400000000000011, 2: -0.123124}}
EDIT
A more dynamic method and one that would reduce the need to create a temporary df:
In [121]: t="""abc -0.123 0.6524 0.325 foo -0.9808 0.874 -0.2341 bar 0.23123 -0.123124 -0.1232"""
Further update
Actually you do not need to read first, the column length can be implicitly obtained by the number of columns in the first column:
In [128]: t="""abc -0.123 0.6524 0.325 foo -0.9808 0.874 -0.2341 bar 0.23123 -0.123124 -0.1232""" cols = pd.read_csv(io.StringIO(t), sep='\s+', usecols=[0], header=None)[0].values df = pd.read_csv(io.StringIO(t), sep='\s+', header=None, usecols = list(range(1, len(cols)+1)), names = cols) df.to_dict() Out[128]: {'abc': {0: -0.12300000000000001, 1: -0.98080000000000001, 2: 0.23123000000000002}, 'bar': {0: 0.32500000000000001, 1: -0.2341, 2: -0.1232}, 'foo': {0: 0.65239999999999998, 1: 0.87400000000000011, 2: -0.123124}}
Edchum
source share