webcrew webcrew - 11 months ago 26
Python Question

python list parsing example

I'd like to know how to parse (or split) and element of a list?

I have a list of lists (of string) such as:

resultList = [['TWP-883 PASS'], ['TWP-1080 PASS'], ['TWP-1081 PASS']]


resultList[0] = ['TWP-883 PASS']
resultList[1] = ['TWP-1080 PASS']

essentially, I need a variable for the two entries in each element of the list. For example:

issueId = 'TWP-883'
status = 'PASS'

What would allow for iterating through this list and parsing such as above?

jDo jDo

I would use list and dictionary comprehensions to turn your list of lists into a list of dictionaries with the keys issueId and status:

resultList = [['TWP-883', 'PASS'], ['TWP-1080', ' PASS'], ['TWP-1081', ' PASS'], ['TWP-1082', ' PASS'], ['TWP-884', ' FAIL'], ['TWP-885', ' PASS']]

result_dicts = [{("issueId","status")[x[0]]:x[1] for x in enumerate(lst)} for lst in resultList]


I get the impression that the resultList is actually not a list of lists containing two values (issueId and status) but a list of lists containing a single string; e.g. ['TWP-883 PASS'] and not ['TWP-883', 'PASS']. If that's the case, use this instead:

result_dicts = [{("issueId","status")[x[0]]:x[1] for x in enumerate(lst[0].split())} for lst in resultList]

Lookups can now be done in this way:

>>> result_dicts[0]
{'status': 'PASS', 'issueId': 'TWP-883'}
>>> result_dicts[0]["status"]
>>> result_dicts[0]["issueId"]
>>> result_dicts[3]["issueId"]

To declare variables for each value in each dictionary in the list and print them, use the code below. There was a space in all but one of the statuses so I called strip() on them when printing to align everything nicely:

for entry in result_dicts:
    issueId = entry["issueId"]
    status = entry["status"]
    print("The status of {0: <10} is {1}".format(issueId, status.strip()))


The status of TWP-883    is PASS
The status of TWP-1080   is PASS
The status of TWP-1081   is PASS
The status of TWP-1082   is PASS
The status of TWP-884    is FAIL
The status of TWP-885    is PASS