使用robot fram提取字典列表中特定键的所有值

2024-10-02 10:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道如何使用robot框架为下面的字典列表中的键“name”提取所有值。请帮帮我。在

{'data': [{'attributes': {'name': 'Acura'},
           'id': 'de3fe2a2-eaa1-45d8-8d6b-298e0b2d0666',
           'type': 'brands'},
          {'attributes': {'name': 'Alfa Romeo'},
           'id': '52b33ad8-71ab-4fdb-b877-a6080e86439c',
           'type': 'brands'},
          {'attributes': {'name': 'Audi'},
           'id': '5f627b7a-193a-40a0-9db7-b8b504177435',
           'type': 'brands'},
          {'attributes': {'name': 'BMW'},
           'id': 'dad04367-2248-45b3-b523-0be7cc7bfbad',
           'type': 'brands'},
          {'attributes': {'name': 'Buick'},
           'id': '64f77989-3007-41f5-b5c4-8cb5f4a25d45',
           'type': 'brands'},
          {'attributes': {'name': 'Cadillac'},
           'id': 'a457ba4e-5f74-4b9a-9316-d26962284983',
           'type': 'brands'},
          {'attributes': {'name': 'Chevrolet'},
           'id': '118e4876-993d-4ad0-91f4-ae3d25b1e5f5',
           'type': 'brands'}],
 'meta': {'total': 48}}

Tags: name框架id列表data字典typerobot
3条回答

d是字典的名称。可以使用以下代码提取名称:

names = [a['attributes']['name'] for a in d['data']]

结果:

^{pr2}$

你可以这样做

>>> [ i['attributes']['name'] for i in a['data']]
['Acura', 'Alfa Romeo', 'Audi', 'BMW', 'Buick', 'Cadillac', 'Chevrolet']

其中a是字典的名称。在

在这个SO question中,引用常规Python字典时会出现点表示法问题。通过将常规Python Dict转换为特定于机器人的DotDict,解决了这个问题。在

或者,如果上面的数据是静态的,您可以考虑从Yaml file导入它,这也允许您使用robot点表示法。在

关于循环和获取名称,那么假设字典被分配给变量D并存储在一个名为dict.py的文件中,那么这将允许您获取名称:

*** Settings ***
Variables    dict.py
*** Test Cases ***
test
    Log To Console    \n    
    :FOR    ${node}    IN    @{d['data']}
    \    Log To Console    ${node['attributes']['name']}

这将导致以下输出:

^{pr2}$

相关问题 更多 >

    热门问题