Search code examples
pythonlistsplitstring-parsing

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']]

where:

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?


Solution

  • Note: I changed this answer to reflect an edit of the question. Specifically, I added a split() to separate the strings in the nested lists into two strings (issueId and status).


    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']]
    
    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'
    >>> result_dicts[0]["issueId"]
    'TWP-883'
    >>> result_dicts[1]
    {'status': 'PASS', 'issueId': 'TWP-1080'}
    >>> 
    

    To declare variables for each value in each dictionary in the list and print them, use the code below:

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

    Output:

    The status of TWP-883    is PASS
    The status of TWP-1080   is PASS
    The status of TWP-1081   is PASS