从字典列表中访问字典值

时间:2016-07-13 01:03:42

标签: dictionary robotframework

我正在使用一个关键字返回一个字典列表,如下所示。如果我遍历字典,我可以得到值。例如,

${vPools} =      list all vpools
: FOR    ${Item}    IN    @{vPools}
\    ${vPoolID} =     ${Item["VPoolID"]}

有没有办法直接访问值而不循环?像

这样的东西
${vPoolID} =   @{vPools[0]}["VPoolID"]

第一个列表项?我一直在尝试不同的东西,但似乎找不到合适的食谱。

17:23:30.815    INFO    [
    {
        "GroupType": 3, 
        "GroupTypeEnum": 3, 
        "Name": "GS - Flash - Protection: 1 - QoS: Gold", 
        "OptimizationSetting": 0, 
        "OptimizationSettingEnum": 0, 
        "PhysicalPoolID": "7efaf334-b723-4be6-af56-3a626562b553", 
        "ProtectionSetting": 1, 
        "QoSClassPriorityID": 1, 
        "Secured": false, 
        "TotalCapacity": 0, 
        "UsedCapacity": 0, 
        "VPoolID": "be7d518e-9851-4ad5-bd59-c7987fc3dd9b"
    }, 
    {
        "GroupType": 3, 
        "GroupTypeEnum": 3, 
        "Name": "GS - Flash - Protection: 1 - QoS: Silver", 
        "OptimizationSetting": 0, 
        "OptimizationSettingEnum": 0, 
        "PhysicalPoolID": "7efaf334-b723-4be6-af56-3a626562b553", 
        "ProtectionSetting": 1, 
        "QoSClassPriorityID": 2, 
        "Secured": false, 
        "TotalCapacity": 0, 
        "UsedCapacity": 0, 
        "VPoolID": "1a82e650-589e-4077-878b-48eea7211278"
    }, 
    {
        "GroupType": 3, 
        "GroupTypeEnum": 3, 
        "Name": "GS - Flash - Protection: 1 - QoS: Bronze", 
        "OptimizationSetting": 0, 
        "OptimizationSettingEnum": 0, 
        "PhysicalPoolID": "7efaf334-b723-4be6-af56-3a626562b553", 
        "ProtectionSetting": 1, 
        "QoSClassPriorityID": 3, 
        "Secured": false, 
        "TotalCapacity": 0, 
        "UsedCapacity": 0, 
        "VPoolID": "5a082095-cbb5-460a-a0fc-0a8dc90d007d"
    }
]()

3 个答案:

答案 0 :(得分:2)

是的,如果您使用extended variable syntax,则可以访问嵌套集合。在使用DatabaseLibrary和SudsLibrary时,这非常方便。确保将键和索引放在花括号内,并将键放在引号中。

List of Dictionaries
    ${a}    Create Dictionary    a=1    b=2
    ${b}    Create Dictionary    x=5    y=7
    ${stuff}    Create List    ${a}    ${b}
    ${item}    Set Variable    ${stuff[0]['b']}
    Should Be Equal    ${stuff[1]['x']}    5

所以试试:

${vPoolID}    Set Variable    ${vPools[0]["VPoolID"]}

由于您引用的是单个项目,请不要使用@,而是使用$。

答案 1 :(得分:1)

Collections library有关键字Get From Dictionary。我认为这正是你要找的:

*** Settings ***
Library    Collections

*** Test Cases ***
Dictionary
    ${dict1}=      Create Dictionary     GroupType=3    VPoolID=be7d518e-9851-4ad5-bd59-c7987fc3dd9b
    ${dict2}=      Create Dictionary     GroupType=3    VPoolID=1a82e650-589e-4077-878b-48eea7211278
    ${vPools}=     Create List           ${dict1}       ${dict2}
    ${vPoolID}=    Get From Dictionary   @{vPools}[0]   VPoolID

答案 2 :(得分:0)

您的右花括号必须在第二组方括号之外。

${vPoolID} =   ${vPools[0]["VPoolID"]}