Search code examples
robotframework

Define a list of dictionaries in Robot Framework


Is there a way of defining, in the Variables section of a robot framework file (.rst), a list of dictionaries (or list of lists)? This should be very straighforward, even for a Robot novice, but I'm struggling to do it. To make things clear, I need something like this:

`*** Variables ***
 @{list_of_dicts}    [{'name': 'Alice', 'age': 25},
                      {'name': 'Bob', 'age': 30},
                      {'name': 'Charlie', 'age': 35}]

*** Keywords ***
Example Keyword
    : FOR    ${dict}    IN    @{list_of_dicts}
    \    Log    ${dict['name']} is ${dict['age']} years old`

I tried varying the posted code in several ways.

Robot Version: 2.9.2


Solution

  • Regretfully, no, it's painfully not-straightforward using just RF syntax - you have to define each dict as a var, and then include them individually in the list variable:

    *** Variables ***
    &{dict1}    key1=value1    key2=value2
    &{dict2}    keyY=valueY    keyX=valueX
    @{list_of_dicts}    ${dict1}    ${dict2}
    

    There is an alternative though - the inline evaluation technique; it for sure will work inside cases and keywords (I've used it for exactly this purpose - a list of dicts to later serialize as json), but I don't know does it work in the Variables section, you have to try it out.
    If it does, it'll look like this - a direct python statement or expression inside ${{}}(double curly brackets):

    *** Variables ***
    ${list_of_dicts}    ${{ [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 35}] }} 
    

    If it doesn't (work there) - you can do it in a keyword, call Set Suite Variable on the variable, and have that keyword called in Suite Setup (that goes under the moto "life is a series of workarounds" :))