Print multiple YAML lists in a dictionary

I am new to python programming. The input file X.yaml contains a list of lists of dictionaries. I am trying to print a list and its subscription items.

Input: X.Yaml

    entities:
        - level: undefined
          name: a
          refs:
              - b
          reqs: []
        - level: undefined
          name: c
          refs:
              - b
          reqs: []

      

code:

data = yaml.load(yamlfile)
for entity in data["entities"]:
     #Needed help here.

      

Desired output:

-name: a
 refs:
     - b
 reqs: []
-name: c
 refs:
    - b
 reqs: []

      

+3


source to share


1 answer


Use yaml.dump()

with default_flow_style=False

:

>>> print yaml.dump(data['entities'], default_flow_style=False)
- level: undefined
  name: a
  refs:
  - b
  reqs: []
- level: undefined
  name: c
  refs:
  - b
  reqs: []

      

And if you don't want a "level", first remove this from the objects:



>>> new_entities = [{key: value for key, value in entity.items() if key != 'level'}
...                 for entity in data['entities']]
>>>
>>> print yaml.dump(new_entities, default_flow_style=False)
- name: a
  refs:
  - b
  reqs: []
- name: c
  refs:
  - b
  reqs: []

>>>

      

Edit: if list and vocabulary concepts are confusing, this is the long (and lower) way of writing:

>>> new_entities = []
>>> for entity in data['entities']:
...     new_ent = {}
...     for key, value in entity.items():
...         if key != 'level':
...             new_ent[key] = value
...     new_entities.append(new_ent)
...
>>> # then dump `new_entities`

      

0


source







All Articles