0

I have following YAML file with disrupted numbering:

aaa:
  bbb:
    ccc:
      1:
        ddd: '123'
        eee: '123'
        fff: 'abc'
        ggg: 'abc'
        hhh: '123'
     4:
        ddd: '123'
        eee: '123'
        fff: 'abc'
        ggg: 'abc'
        hhh: '123'
      5:
        ddd: '123'
        eee: '123'
        fff: 'abc'
        ggg: 'abc'
        hhh: '123'
      9:
        ddd: '123'
        eee: '123'
        fff: 'abc'
        ggg: 'abc'
        hhh: '123'

Is there a way to implement automatic numbering in Python 2.7 for such file? So that keys are in correct order?

The desired file then would be:

aaa:
  bbb:
    ccc:
      1:
        ddd: '123'
        eee: '123'
        fff: 'abc'
        ggg: 'abc'
        hhh: '123'
     2:
        ddd: '123'
        eee: '123'
        fff: 'abc'
        ggg: 'abc'
        hhh: '123'
      3:
        ddd: '123'
        eee: '123'
        fff: 'abc'
        ggg: 'abc'
        hhh: '123'
      4:
        ddd: '123'
        eee: '123'
        fff: 'abc'
        ggg: 'abc'
        hhh: '123'

I did not find such option in Python yaml library. Another option would be convert to JSON, but in this case it is not preferred - as I also need to save the comments.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Curious: why use an associative array at all instead of a list? – chepner Mar 18 '22 at 13:09
  • 1
    It is unlikely you'll find auto-numbering in any library for any format such as YAML, JSON, INI, etc unless such a thing is part of the format's specification — for reasons the ought to be obvious. – martineau Mar 18 '22 at 13:24
  • There's also the trivial step of reading this into a `dict`, replacing the `ccc` value with a new `dict(enumerate(old['ccc'].values(), start=1))`, then writing it back to the file. That can effect the *formatting* in ways you don't want, but won't affecting anyone else that parses the file. – chepner Mar 18 '22 at 13:31
  • If you need to preserve the comments, you need to use `ruamel.yaml`, but you will need to do the renumbering after loading yourself, but that is trivial. Why are you still on Python 2.7? – Anthon Apr 30 '22 at 16:27

0 Answers0