Search code examples
pythonnestedpyyaml

Dump nested list with pyyaml fails


I am trying to save a nested list with yaml. The list is created from a numpy object array. However, it does only save the first entry of the list correctly. For the second entry it raises a numpy error, even though the type is a list.

Any ideas someone? Thank you!

import yaml
import numpy as np

data = np.array([[2208.1228557937147,
  2093.0250284887197,
  1980.855846468757,
  2069.7967485855784,
  1960.1406346512429,
  1930.101846442551,
  1468.8137885997755,
  1286.0166724959329,
  1463.023812516738,
  1707.6732969947416,
  1812.096699802357,
  1731.3333318300395,
  1387.923626074238,
  1246.3505835697508,
  1367.3717291628407,
  465.3374594677858,
  426.498753786384,
  301.73353032485784],
 [2163.211451548863,
  2093.0250284887197,
  1980.855846468757,
  2208.1228557937147]], dtype='object')

my_list = data.tolist()
[print(type(l)) for l in my_list]

project = {}
project['test'] = my_list

with open('test.yml', 'w') as f:
    yaml.dump(project, f)

The file looks like this:

test:
- - 2208.1228557937147
  - 2093.0250284887197
  - 1980.855846468757
  - 2069.7967485855784
  - 1960.1406346512429
  - 1930.101846442551
  - 1468.8137885997755
  - 1286.0166724959329
  - 1463.023812516738
  - 1707.6732969947416
  - 1812.096699802357
  - 1731.3333318300395
  - 1387.923626074238
  - 1246.3505835697508
  - 1367.3717291628407
  - 465.3374594677858
  - 426.498753786384
  - 301.73353032485784
- - !!python/object/apply:numpy.core.multiarray.scalar
    - &id001 !!python/object/apply:numpy.dtype
      args:
      - f8
      - false
      - true
      state: !!python/tuple
      - 3
      - <
      - null
      - null
      - null
      - -1
      - -1
      - 0
    - !!binary |
      HJ5gQ2zmoEA=
  - !!python/object/apply:numpy.core.multiarray.scalar
    - *id001
    - !!binary |
      CrmI0AxaoEA=
  - !!python/object/apply:numpy.core.multiarray.scalar
    - *id001
    - !!binary |
      1UYEY2zznkA=
  - !!python/object/apply:numpy.core.multiarray.scalar
    - *id001
    - !!binary |
      QmD05j5AoUA=

Solution

  • pyyaml cannot deal with numpy arrays. One has to pass a list of lists.