How to convert list of tuple to list?

1,220 views
Skip to first unread message

Winston Ma

unread,
Jan 19, 2014, 11:26:32 PM1/19/14
to robotframe...@googlegroups.com
Hi users,

I use DatabaseLibrary to collect the result from database. But it turns out that the item returned is a list of tuple (e.g. [ ('A',) | ('B',) | ('C',) | ('D',) | ('E',) | ('F',) | ('G',) ]. I would like to convert this into a list (by removing the tuples bracket).

In python there is a zip function which I can obtain a list from a list of tuples, but I have no idea how to do this in robot framework.

Thanks in advance

Kevin O.

unread,
Jan 22, 2014, 11:01:56 AM1/22/14
to robotframe...@googlegroups.com
There are three possible approaches I see here:
Use Evaluate to do a little Python without having to write a Python keyword - does not work with all variable types, but is short and sweet
Use a FOR loop and iterate over the rows and make your own list - fills up logs but safe to use
Use a Python keyword - hard if you have never written a Python library

If a variable in Robot has a string representation that can be used by eval, the variable can be used directly in Evaluate. When a variable does not have a string representation that cannot be used by eval to make the same object (eval(repr(x)) != x), you would have to write a keyword in Python to work with a variable directly or use a FOR loop. In the case of a rowset, you should be able to use the variable in an Evaluate expression.
Below there are two ways of extracting the first column - with Evaluate and with a for loop. The for loop approach is safer than Evaluate, but fills up the log if the collection is large.

    ${row set}    Evaluate     [ ('A',) , ('B',) , ('C',) , ('D',) , ('E',) , ('F',) , ('G',) ]    # just to reproduce result set from DB
    ${first column A}=    Evaluate    [x[0] for x in ${row set}]    # works if row set's string representation can be passed to eval to get same object
    Log List    ${first column A}
    ${first column B}=    Create List
    :FOR    ${row}    IN    @{row set}
    \    Append To List    ${first column B}    ${row[0]}
    Log List    ${first column B}
    Lists Should Be Equal    ${first column A}    ${first column B}

And finally, in Python, a keyword like this would do the trick:

def get_first_column(row_set):
    return [x[0] for x in row_set]
Reply all
Reply to author
Forward
0 new messages