【问题标题】:Subtracting two dict values in Robot Framework在 Robot Framework 中减去两个 dict 值
【发布时间】:2020-07-21 20:44:45
【问题描述】:

我有两个字典

${Dict1}={'Test_1': {'l': 307, 'T': 290, 'R': 5785, 'Bo': 4693} ,'Test_2': {'l': 307, 'T': 290, 'R': 5785, 'B': 4693}} 
${Dict2}={'TestB_3': {'l': 310, 'T': 295, 'R': 5785, 'Bo': 4693} ,'TestB_4': {'l': 307, 'T': 290, 'R': 5785, 'B': 4693}} 

我想减去并得到这样的结果 ${Dict1}-${Dict2}

${Result} = {'Test_1': {'l': -3 , 'T': -5, 'R': 0, 'Bo': 0} ,'Test_2': {'l': 0, 'T': 0, 'R': 0, 'B': 0}

我知道如何在 Python 中做,但是在 Robot 框架中,我不明白

在 Python 中,

我们做类似的事情

for key1,Key2 in zip(dict1.key, dict2.key):
     result[key1]=dict[Key1]-dict[key2]

在python的ROBOT框架中是否有这样的东西

更新更多信息

${x2}    Create Dictionary    x2=2
${x1}    Create Dictionary    x1=5
FOR    ${key_of_Orginal}    ${key_of_Actual}    IN ZIP    @{x2}    @{x1}
Log    ${key_of_Orginal}
Log    ${key_of_Actual}
END

会报这个错误

Starting test: ManualMargin.Test1.Test8
20200410 14:41:52.061 :  INFO : ${x2} = {'x2': '2'}
20200410 14:41:52.063 :  INFO : ${x1} = {'x1': '5'}
20200410 14:41:52.064 :  FAIL : FOR IN ZIP items must all be list-like, got string.
Ending test:   Test8

【问题讨论】:

    标签: python python-3.x robotframework


    【解决方案1】:

    您的机器人框架格式的 Python 代码:

    FOR    ${key1}    ${key2}    IN ZIP    ${dict1}    ${dict2}
        ${value}=    Evaluate    $dict1[$key1] - $dict2[$key2]
        Set do Dictionary    ${result}    ${key1}    ${value}
    END
    

    如您所见,这里的语法几乎相同。

    您采用的方法有很强的依赖性 - 两个字典具有相同的键,它们的顺序相同,并且在检索它们时会保留该顺序(最后一个适用于 python 版本 3.6+) .否则,您可能会减去不同键的值。
    一个更可靠的方法是只迭代两者中的一个的键,确保它存在于第二个中,然后进行计算。例如:

    FOR    ${key1}    IN    @{dict1}
        ${exists}=    Run Keyword And Return Status    Dictionary Should Contain Key    ${dict2}   ${key1}
        Continue For Loop If    not ${exists}    # the other doesn't have it, cannot do the calc
        ${value}=    Evaluate    $dict1[$key1] - $dict2[$key1]
        Set do Dictionary    ${result}    ${key1}    ${value}
    END
    

    【讨论】:

    • FOR IN ZIP items must all be list-like, got string 我看到了这个错误。我尝试了第一种方法
    • ${dict1}${dict2} 变量必须是正确的字典,您很可能传递的是 json 字符串。
    • 我将 Dict1 和 Dict2 作为我的关键字中的参数,格式如上。像这样[Arguments] ${Dict1} ${Dict2}
    • 只是为了获取更多信息,我在变量进入 for 循环之前记录了它,就像这样。 {'C:\page268.tif': {'L': 307, 'T': 290, 'R': 5785, 'B': 4693}} 。这是相同的格式情况下另一个变量也是。
    • IN ZIP 需要一个变量引用,而不是扩展一个;我已经更新了答案。
    【解决方案2】:

    一种解决方案是用 Python 编写一个函数,如下所示,并将其添加到用户定义的库中,然后将该库导入您想要使用它的位置。

    def sub_dict(dict1, dict2):
        result = {}
        for tuple in zip(dict1.keys(), dict2.keys()):
            result[tuple[0]] = dict1[tuple[0]] - dict2[tuple[1]]
        return result
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多