Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert multiline "tabular" string to dictionary

I have a string that looks something like this:

name1                            pass  blue  n/a
name-6t56-yt6                    fail  red   n/a
name-45                          pass  blue  n/a
name-6t567-yt6                   fail  red   n/a

I want to extract data from the first 2 columns and would ideally store it in a dictionary in the following manner:

[{'type': 'name1', 'status': 'pass'}, {'type': 'name-6t56-yt6', 'status': 'fail'}, {'type': 'name-45', 'status': 'pass'}, {'type': 'name-6t567-yt6', 'status': 'fail'}]

Any ideas of how to approach this?

Note that this is a multi-line string(in utf-8 format).

like image 420
crypticgamer Avatar asked Jun 10 '26 22:06

crypticgamer


1 Answers

Assuming you want a list:

Setup:

>>> s = '''name1                            pass  blue  n/a
... name-6t56-yt6                    fail  red   n/a
... name-45                          pass  blue  n/a
... name-6t567-yt6                   fail  red   n/a'''

Construct result:

>>> [dict(zip(('type', 'status'), line.split(maxsplit=2)[:2])) for line in s.splitlines()]
[{'type': 'name1', 'status': 'pass'}, {'type': 'name-6t56-yt6', 'status': 'fail'}, {'type': 'name-45', 'status': 'pass'}, {'type': 'name-6t567-yt6', 'status': 'fail'}]
like image 183
timgeb Avatar answered Jun 12 '26 11:06

timgeb