notmenotme
notmenotme

Reputation: 51

Iterate over a yaml list in python

I am trying to set up a yaml file but I am having trouble. I would like layers to contain a list of layer names, and then for each layer name I would like to list the associated styles. This is what I have so far:

wms-server:
    name: weather
    url: ${CACHE_WMS}
    layers:
    - name: RADAR_1KM_RRAI
    styles: [TEMPERATURE, TEMPWINTER-LINEAR, TEMPWINTER, TEMPSUMMER-LINEAR, TEMPSUMMER, TEMPERATURE-LINEAR]
    - name: GDPS.ETA_TT
    styles: [BOLD, SIMPLE]

What I have so far is incorrect but I don't know how to fix it.

Upvotes: 1

Views: 2029

Answers (1)

zedfoxus
zedfoxus

Reputation: 37059

It seems like your yaml file needs to be formatted a bit. Try changing it like so:

wms-server:
  name: weather
  url: ${CACHE_WMS}
  layers:
    - name: RADAR_1KM_RRAI
      styles: [TEMPERATURE, TEMPWINTER-LINEAR, TEMPWINTER, TEMPSUMMER-LINEAR, TEMPSUMMER, TEMPERATURE-LINEAR]
    - name: GDPS.ETA_TT
      styles: [BOLD, SIMPLE]

Then, you can list out the data from it using Python (do pip3 install pyyaml if you don't have yaml library).

import yaml
fi = open('yamlfile', 'r')
data = yaml.load(fi, Loader=yaml.FullLoader)
print(data)

for layer in data['wms-server']['layers']:
    print(layer['name'])
    print(layer['styles'])

That'll print:

RADAR_1KM_RRAI
['TEMPERATURE', 'TEMPWINTER-LINEAR', 'TEMPWINTER', 'TEMPSUMMER-LINEAR', 'TEMPSUMMER', 'TEMPERATURE-LINEAR']
GDPS.ETA_TT
['BOLD', 'SIMPLE']

Upvotes: 1

Related Questions