For loop over dictionary in Robot Framework
Another workaround is to use the keyword "Get From Dictionary" during the for loop.
Loop through and Log key and value in dict
[Documentation] Loops through each key and stores the key value
... in a variable that can be used during the for
... loop, as if you were iterating through python
... with "for key, value in dict.iteritems()".
&{mydict} Create Dictionary a=1 b=2
:FOR ${key} IN @{mydict.keys()}
\ ${value}= Get From Dictionary ${mydict} ${key}
\ Log ${key}, ${value}
reference: http://robotframework.org/robotframework/latest/libraries/Collections.html#Get%20From%20Dictionary
Loop Through Dict
&{mydict} Create Dictionary a=1 b=2
:FOR ${key} IN @{mydict.keys()}
\ Log ${mydict["${key}"]}
Loop Through Dict And Multiplicate Values
&{mydict} Create Dictionary a=1 b=2
:FOR ${key} IN @{mydict.keys()}
\ ${new_value} Evaluate ${mydict["${key}"]}*2
\ Set To Dictionary ${mydict} ${key}=${new_value}
Log ${mydict}
To iterate over a dictionary's keys, you don't have to use any python method at all, but insted use the Robotframework's @
modifier for list expansion. For example:
${mydict} Create Dictionary a=1 b=2
:FOR ${key} IN @{mydict}
\ Log The current key is: ${key}
# there are at least to ways to get the value for that key
# "Extended variable syntax", e.g. direct access:
\ Log The value is: ${mydict['${key}']}
# or using a keyword from the Collections library:
\ ${value}= Get From Dictionary ${mydict} ${key}
\ Log The value through Collections is: ${value}
The loop over the keys works straightaway, because in python a list()
cast of a dictionary is actually the list of its keys. Sample code:
mydict = {'a': 1, 'b': 2}
print(list(mydict))
# the output is
# ['a', 'b']
There is a python's dict method items()
that iterates over the dictionary and returns a tuple of key, value. Regretfully, there is no direct substitute in Robot Framework's for loops, yet - this can be done with the Get Dictionary Items
keyword. It returns a one-dimensional list, in the form
['key1', value_of_key1, 'key2', value_of_key2,]
Combining that with the @
list expansion, you can get both the key and the value in each cycle:
${mydict} Create Dictionary a=1 b=2
${items} Get Dictionary Items ${mydict}
:FOR ${key} ${value} IN @{items}
\ Log The current key is: ${key}
\ Log The value is: ${value}