Raxso
Raxso

Reputation: 35

python to loop over yaml config

Basically I want to iterate over yaml file, but it only print the last values of the yaml config.

Code:

for application in config['applications']:

    default_cname = '%s-%s.%s.elasticbeanstalk.com' % (application['cname'], application[‘name’], config['region'])

    print (default_cname)

YAML File:

sqa:
  region: ap-northeast-1
  applications:
    - name: admin
      cname: wp-kb-web
      name: web
      cname: wp-kb

Expected Output:

wp-kb-web-admin.ap-northeast-1.elasticbeanstalk.com
wp-kb-web.ap-northeast-1.elasticbeanstalk.com

Upvotes: 0

Views: 1275

Answers (1)

Guillaume
Guillaume

Reputation: 6029

You miss a - to start the second application definition in your YAML. Without it, there is one single item in your list where the latest attributes overrides the first (duplicate) ones:

import yaml
yaml.load('''sqa:
  region: ap-northeast-1
  applications:
    - name: admin
      cname: wp-kb-web
      name: web
      cname: wp-kb'''

{'sqa': {'applications': [{'cname': 'wp-kb', 'name': 'web'}], 'region': 'ap-northeast-1'}}

yaml.load('''sqa:
  region: ap-northeast-1
  applications:
    - name: admin
      cname: wp-kb-web
    - name: web
      cname: wp-kb'''

{'sqa': {'applications': [{'cname': 'wp-kb-web', 'name': 'admin'}, {'cname': 'wp-kb', 'name': 'web'}], 'region': 'ap-northeast-1'}}

Upvotes: 1

Related Questions