首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python中迭代嵌套列表/字典

在python中迭代嵌套列表/字典
EN

Stack Overflow用户
提问于 2020-12-08 00:38:10
回答 2查看 287关注 0票数 0

我正在尝试解析一个yaml文件- https://github.com/open-telemetry/opentelemetry-specification/blob/master/semantic_conventions/resource/cloud.yaml

我使用以下代码

代码语言:javascript
复制
with open('cloud.yaml') as f:
    my_dict = yaml.safe_load(f)

print(my_dict)

生成以下字典:

代码语言:javascript
复制
{'groups': [{'id': 'cloud', 'prefix': 'cloud', 'brief': 'A cloud infrastructure (e.g. GCP, Azure, AWS)\n', 'attributes': [{'id': 'provider', 'type': {'allow_custom_values': True, 'members': [{'id': 'AWS', 'value': 'aws', 'brief': 'Amazon Web Services'}, {'id': 'Azure', 'value': 'azure', 'brief': 'Microsoft Azure'}, {'id': 'GCP', 'value': 'gcp', 'brief': 'Google Cloud Platform'}]}, 'brief': 'Name of the cloud provider.\n', 'examples': 'gcp'}, {'id': 'account.id', 'type': 'string', 'brief': 'The cloud account ID used to identify different entities.\n', 'examples': ['opentelemetry']}, {'id': 'region', 'type': 'string', 'brief': 'A specific geographical location where different entities can run.\n', 'examples': ['us-central1']}, {'id': 'zone', 'type': 'string', 'brief': 'Zones are a sub set of the region connected through low-latency links.\n', 'note': 'In AWS, this is called availability-zone.\n', 'examples': ['us-central1-a']}]}]}

我想迭代这些元素并提取以下值

  1. id -
  2. all attributes -> id - provider;id - account.id;id -region;id -zone
  3. 成员- aws,azure,gcp

我试图使用下面的代码来检查所有的键值

代码语言:javascript
复制
for groups in my_dict.values():
    print(groups)

输出是

代码语言:javascript
复制
[{'id': 'cloud', 'prefix': 'cloud', 'brief': 'A cloud infrastructure (e.g. GCP, Azure, AWS)\n', 'attributes': [{'id': 'provider', 'type': {'allow_custom_values': True, 'members': [{'id': 'AWS', 'value': 'aws', 'brief': 'Amazon Web Services'}, {'id': 'Azure', 'value': 'azure', 'brief': 'Microsoft Azure'}, {'id': 'GCP', 'value': 'gcp', 'brief': 'Google Cloud Platform'}]}, 'brief': 'Name of the cloud provider.\n', 'examples': 'gcp'}, {'id': 'account.id', 'type': 'string', 'brief': 'The cloud account ID used to identify different entities.\n', 'examples': ['opentelemetry']}, {'id': 'region', 'type': 'string', 'brief': 'A specific geographical location where different entities can run.\n', 'examples': ['us-central1']}, {'id': 'zone', 'type': 'string', 'brief': 'Zones are a sub set of the region connected through low-latency links.\n', 'note': 'In AWS, this is called availability-zone.\n', 'examples': ['us-central1-a']}]}]

我想单独打印所有值,例如云、云基础设施(例如GCP、Azure、AWS)\n等。

我需要的输出是打印以下值:

代码语言:javascript
复制
cloud, A cloud infrastructure (e.g. GCP, Azure, AWS).
cloud.provider,, Name of the cloud provider.
cloud.provider.member, AWS, Amazon Web Services
cloud.provider.member, azure, Microsoft Azure
cloud.provider.member, GCP, Google Cloud Platform
cloud.account.id, string, The cloud account ID used to identify different entities.
cloud.region, string, A specific geographical location where different entities can run.    
.
.
.
.
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-12-08 03:05:12

还可以以泛型方式实现,以验证“type”中的值是否为dict实例:

假设变量parsed_dict在解析jaml文件后得到结果:

代码语言:javascript
复制
def remove_end_of_line_char(line_text):
    if len(line_text) > 0 and line_text[-1] == '\n':
        line_text = line_text[:-1]

    return line_text


data_groups = parsed_dict["groups"]
for group in data_groups:
    msg = remove_end_of_line_char(f"{group['id']}, {group['brief']}")
    print(msg)
    attributes_list = group["attributes"]
    for attribute in attributes_list:
        attr_type = attribute['type']
        if isinstance(attr_type, dict):
            print(f"{group['id']}.{attribute['id']},, {remove_end_of_line_char(attribute['brief'])}")
            cloud_provider_member_prefix = f"{group['id']}.{attribute['id']}.member, "
            for member in attr_type['members']:
                print(f"{cloud_provider_member_prefix}{member['id']}, {member['brief']}")
        else:
            msg = remove_end_of_line_char(f"{group['id']}.{attribute['id']}, {attribute['type']}, {attribute['brief']}")
            print(msg)
票数 0
EN

Stack Overflow用户

发布于 2020-12-08 02:36:11

这是你的输出字典。我让它可读的

代码语言:javascript
复制
myDict = {
'groups': [
    {
        'id': 'cloud', 
        'prefix': 'cloud', 
        'brief': 'A cloud infrastructure (e.g. GCP, Azure, AWS)\n', 
        'attributes': [
            {
                'id': 'provider', 
                'type': {
                    'allow_custom_values': True, 
                    'members': [
                        {
                            'id': 'AWS', 
                            'value': 'aws', 
                            'brief': 'Amazon Web Services'
                            
                        }, 
                        {
                            'id': 'Azure', 
                            'value': 'azure', 
                            'brief': 'Microsoft Azure'
                            
                        }, 
                        {
                            'id': 'GCP', 
                            'value': 'gcp', 
                            'brief': 'Google Cloud Platform'
                            
                        }
                    ]
                    
                }, 
                'brief': 'Name of the cloud provider.\n',
                'examples': 'gcp'
                
            }, 
            {
                'id': 'account.id', 
                'type': 'string', 
                'brief': 'The cloud account ID used to identify different entities.\n', 
                'examples': ['opentelemetry']}, 
                {
                    'id': 'region', 
                    'type': 'string', 
                    'brief': 'A specific geographical location where different entities can run.\n',
                    'examples': ['us-central1']
                    
                },
                {
                    'id': 'zone', 
                    'type': 'string', 
                    'brief': 'Zones are a sub set of the region connected through low-latency links.\n',
                    'note': 'In AWS, this is called availability-zone.\n',
                    'examples': ['us-central1-a']
                    
                }
        ]
    }
]

}

现在我们可以清楚地看到它。

代码语言:javascript
复制
for v in myDict['groups'][0].items():
    print(v)

输出:

代码语言:javascript
复制
('id', 'cloud')
('prefix', 'cloud')
('brief', 'A cloud infrastructure (e.g. GCP, Azure, AWS)\n')
('attributes', [{'id': 'provider', 'type': {'allow_custom_values': True, 'members': [{'id': 'AWS', 'value': 'aws', 'brief': 'Amazon Web Services'}, {'id': 'Azure', 'value': 'azure', 'brief': 'Microsoft Azure'}, {'id': 'GCP', 'value': 'gcp', 'brief': 'Google Cloud Platform'}]}, 'brief': 'Name of the cloud provider.\n', 'examples': 'gcp'}, {'id': 'account.id', 'type': 'string', 'brief': 'The cloud account ID used to identify different entities.\n', 'examples': ['opentelemetry']}, {'id': 'region', 'type': 'string', 'brief': 'A specific geographical location where different entities can run.\n', 'examples': ['us-central1']}, {'id': 'zone', 'type': 'string', 'brief': 'Zones are a sub set of the region connected through low-latency links.\n', 'note': 'In AWS, this is called availability-zone.\n', 'examples': ['us-central1-a']}])

现在提取像这样的数据。但是,您可以在一个for循环中获取所有值。

代码语言:javascript
复制
data = myDict['groups'][0]
id = data['id']
brief = data['brief']
attr = data['attributes']
mems = attr[0]['type']['members']

print(f"{id},{brief})    

for member in mems:
    print(f"cloud.provider.member.{member['value']}, {member['brief']}")

输出:

代码语言:javascript
复制
cloud,A cloud infrastructure (e.g. GCP, Azure, AWS)

cloud.provider.member.aws, Amazon Web Services
cloud.provider.member.azure, Microsoft Azure
cloud.provider.member.gcp, Google Cloud Platform
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65191475

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档