遍历 YAML 对象 [英] Iterate Through YAML objects

查看:45
本文介绍了遍历 YAML 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 yml 文件

- id: id1
  memberPort: 8080
  instance:
    name: test
    id: q1
    site: us
    dns: dns1
    ip: 1p2
    state: available
- id: id2
  memberPort: 8080
  instance:
    name: test2
    id: q2
    site: us
    dns: dns2
    ip: ip1
    state: available

我想遍历这个并获取 ip print ip1 和 ip2 的 vauls

I want to iterate through this and get the vauls of ip print ip1 and ip2

尝试查看示例并获得以下代码

Tried looking at the examples and got the below code

import yaml
f = open('file.yml')
yaml_file = yaml.safe_load(f)
for entry in yaml_file["id"]:
    print yaml_file[id]["ip"])

但它不起作用

知道如何修复这个 python 谢谢

Any idea how to fix this python Thanks

推荐答案

您将阅读和迭代条目与评估条目混为一谈.将两者分开,如下所示:

You're mixing up reading and iterating over the entries with evaluating them. Keep the two separate, like this:

import yaml
f = open('/tmp/test.yaml')
yaml_file = yaml.safe_load(f)
for entry in yaml_file:
    print(entry)
    print("ID: " + entry['id'])
    print("IP: " + entry['instance']['ip'])

结果:

{'id': 'id1', 'memberPort': 8080, 'instance': {'name': 'test', 'id': 'q1', 'site': 'us', 'dns': 'dns1', 'ip': '1p2', 'state': 'available'}}
ID: id1
IP: 1p2
{'id': 'id2', 'memberPort': 8080, 'instance': {'name': 'test2', 'id': 'q2', 'site': 'us', 'dns': 'dns2', 'ip': 'ip1', 'state': 'available'}}
ID: id2
IP: ip1

这篇关于遍历 YAML 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆