Search code examples
pythonpyyaml

Parsing yaml list and dicts in Python


Using Python3 and pyyaml how can I accomplish the following?

Yaml:

role-templates:
- readonly:
  - step1;
  - step2;
- readwrite:
  - step1;
  - step2
  - step3;

Given a role (readonly or readwrite), I need a list of steps.

This doesn't work because I have a list and not a dict.

with open('dbconfig.yaml') as f:
    baseConfig = yaml.safe_load(f)

roleType = 'readonly'
roleSteps = baseConfig['role-templates'][roleType]

The above code fails to index into role-templates.

Alternatively, I was starting to head down this route:

roleType = 'readonly'
roleSteps =  first_true(roleTemplates, None, lambda x: x == roleType)

How can I extract the steps for a given role?


Solution

  • If you have no way to change the YAML file, and have to deal with this after loading:

    d = yaml.safe_load(io.StringIO("""role-templates:
    - readonly:
      - step1;
      - step2;
    - readwrite:
      - step1;
      - step2
      - step3;
    """))
    
    d['role-templates'] = {k: v for d in d['role-templates'] for k, v in d.items()}
    

    If you are the only user of that YAML definition, then change it:

    d = yaml.safe_load(io.StringIO("""role-templates:
     readonly:
      - step1;
      - step2;
     readwrite:
      - step1;
      - step2
      - step3;
    """))
    

    In either case, the resulting content of d['role-templates'] is a proper dict, and you can get e.g.:

    >>> d['role-templates'].get('readonly')
    ['step1;', 'step2;']