是否有正确的方法在RF中循环字典? 我使用了pythonic方式,但失败了:
:FOR ${key} ${value} IN &{dict}
输出: FOR循环值的数量应该是其变量的倍数。得到2个变量,但有1个值。
同样,当我将字典指向为标量变量时。但是我无法在文档中找到一个例子。 有人解决了吗?
P.S。
我知道解决方法,你使用kw。获取字典键和获取字典值,然后,更新您使用的值设置为字典$ {key} $ {new_value},但这似乎是人类不友好的,并使用几个for循环迭代而不是一个。
答案 0 :(得分:11)
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}
答案 1 :(得分:6)
要遍历字典的键,您根本不必使用任何python方法,但是insted使用Robotframework的@
修饰符进行列表扩展。例如:
${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}
键上的循环可以直接使用,因为在python中,字典的list()
强制转换实际上是其键的列表。示例代码:
mydict = {'a': 1, 'b': 2}
print(list(mydict))
# the output is
# ['a', 'b']
有一个python的dict方法items()
迭代字典并返回一个key,value元组。遗憾的是,在Robot Framework的for循环中没有直接替代,但是 - 这可以通过the Get Dictionary Items
keyword完成。它以
['key1', value_of_key1, 'key2', value_of_key2,]
将其与@
列表扩展相结合,您可以获得每个周期中的键和值:
${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}
答案 2 :(得分:3)
另一种解决方法是使用关键字" Get From Dictionary"在for循环期间。
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}
参考:http://robotframework.org/robotframework/latest/libraries/Collections.html#Get%20From%20Dictionary
答案 3 :(得分:2)
检查解决方案:
:FOR ${key} IN @{mydict}
# works as @{mydict.keys()}
:FOR ${key} ${value} IN @{mydict.items()}
# doesn't work at all
找到了另一个可行的解决方案:
:FOR ${key} ${value} IN ZIP ${mydict.keys()} ${mydict.values()}
# And another less readable (can work without setters)
:FOR ${el} IN @{mydict.items()}
\ ${key}= Set Variable ${el[0]}
\ ${value}= Set Variable ${el[1]}
答案 4 :(得分:0)
尝试一下(RF:3.2。+):
FOR ${key_value} IN @{mydict.items()}
${key}= set variable ${key_value}[0]
${value}= set variable ${key_value}[1]
log Key: ${key}; Value: ${value}
END
答案 5 :(得分:0)
我发现此版本更易读(使用RF 3.2 +)
FOR ${key} IN @{mydict.items()}
Log To Console ${key}: ${mydict}[${key}]
END
答案 6 :(得分:0)
这也可行:
FOR ${key} IN @{res.keys()}
Log ${key}
END
答案 7 :(得分:0)
FOR ${key} ${value} IN &{dictionary}
Log To Console key = ${key}, value = ${value}
END
这在 RF 3.2.2 中工作正常