Home > Software design >  Parsing yaml file format in python
Parsing yaml file format in python

Time:05-24

I have yaml file in this format. I have chunks of data start with "- Buffer: 0". Need to store that chunks in dictionary and process the data.

- {MinimumRequiredVersion: 1.2.1}
- baran
- afc90a
- [Device 0050, Device 0051, Device 0052, Device 0054, Device 0062, Device 7400, Device 740c]
- AllowNoFreeDims: false
  AssignedDerivedParameters: true
  DataType: 4
  IndexAssignmentsLD: [4, 5, 6, 7]
  IndexUnroll: 3
- - Buffer: 0
    AggressivePerfMode: 1
    AssertFree0ElementMultiple: 1
    AssertFree1ElementMultiple: 1
    ...
  - Buffer: 0
    AggressivePerfMode: 1
    AssertFree0ElementMultiple: 1
    ...
  - Buffer: 0
    AggressivePerfMode: 1
    AssertFree0ElementMultiple: 1
    AssertFree1ElementMultiple: 1
    ...
  - Buffer: 0
    AggressivePerfMode: 1
    AssertFree0ElementMultiple: 1
    AssertFree1ElementMultiple: 1
    ...
  - Buffer: 0
    AggressivePerfMode: 1
    AssertAlphaValue: false
    AssertBetaValue: false
    AssertCEqualsD: false
    AssertMinApproxSize: 3
    ...
  - 1LDSBuffer: 0
    AggressivePerfMode: 1
    AssertAlphaValue: false
    AssertBetaValue: false
    ...
- [2, 3, 0, 1]
- - - [512, 1, 1, 500000]
    - [8, 0.45]
  - - [512, 2, 1, 500000]
    - [8, 0.883]
- null

I used below code to parse the yaml file and print and it works.

with open(filename, "r") as f:
        data = yaml.load(f, yaml.SafeLoader)
        sorted_data = yaml.dump(data)
        print(sorted_data)

I am new to python and this format of yaml file. any pointers how can I extract the chunks of data in a dictionary(may be list also ok) between "- Buffer :0 " to another "- Buffer :0 ". I tried this to get the chunks but not successful. print({data['Buffer]})

CodePudding user response:

data is a list (its elements specified by - in YAML). A list containing the dictionaries you seem to be interested in are thus in data[5] — you can see it is another list by another level of - items. Specifically, data[5][0] is a dictionary (specified by <key>: items in YAML):

{'Buffer': 0, 'AggressivePerfMode': 1, 'AssertFree0ElementMultiple': 1, 'AssertFree1ElementMultiple': 1}

and data[5][0]["Buffer"] is 0.

  • Related