0

I have yml file

- 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

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"])

But it is not working

Any idea how to fix this python Thanks

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Dsyd Shi
  • 3
  • 3

2 Answers2

0

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'])

Result:

{'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
CryptoFool
  • 21,719
  • 5
  • 26
  • 44
0

Once the line yaml_file = yaml.safe_load(f) the data type of yaml_file is a list.
All you have to do is to iterate over it like:

for entry in yaml_file:
   print(entry['instance']['ip'])
balderman
  • 22,927
  • 7
  • 34
  • 52