s = """
ID# VALUE_1 VALUE_2
1 0.1 300
2 0.2 400 (11 - this text is part of C in row 2 but needs to be ignored / removed)
3 0.9 600"""
I am wanting to convert the above string into the formatted dictionary below. The spacing and extra text is like that on purpose. The spacing & noted text should be removed / stripped.
print(my_dict)
{'1': {'VALUE_1': '0.1', 'VALUE_2': '300'}, '2': {'VALUE_1': '0.2', 'VALUE_2': '400'}, '3': {'VALUE_1': '0.9', 'VALUE_2': '600'}}
What I've tried so far:
s = """
ID# VALUE_1 VALUE_2
1 0.1 300
2 0.2 400 (11 - this text is part of C in row 2 but needs to be ignored / removed)
3 0.9 600"""
#Get the columns and assign them to a variable.
columns = s.lstrip().splitlines()[0] #Print the first line of the string
dct = {}
rows = s.lstrip().splitlines()
for data in rows[1:]:
row = data.split()
dct[row[0]] = dict(zip(columns[1:], row[1:]))
print(dct)
This ends up outputting an ugly unformatted looking dictionary :
{'1': {'D': '0.1', '#': '300'}, '2': {'D': '0.2', '#': '400', ' ': 'in', 'V': 'row', 'A': '2', 'L': 'but', 'U': 'needs', 'E': 'to', '_': 'be', '1': 'C', '2': 'ignored'}, '3': {'D': '0.9', '#': '600'}}
I've been unable to incorporate a way to successfully strip out the spaces and extra chunk of data on row2 with my current loop process.