-1

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?

rboarman
  • 8,248
  • 8
  • 57
  • 87
  • 1
    You should look at the structure that represents - `role-templates` is an array of objects. If you're stuck with that YAML, I'd suggest you turn that list into a dict first, but it would be better to start with the right structure from the beginning. – jonrsharpe Aug 27 '21 at 16:44
  • So change the yaml to get the parser to create the objects I need? – rboarman Aug 27 '21 at 16:47
  • 1
    If you _can_ change it, yes. – jonrsharpe Aug 27 '21 at 16:47

1 Answers1

3

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;']
Pierre D
  • 24,012
  • 7
  • 60
  • 96