Can PyYAML dump dict items in non-alphabetical order?

后端 未结 10 785
一向
一向 2020-11-29 03:38

I\'m using yaml.dump to output a dict. It prints out each item in alphabetical order based on the key.

>>> d = {\"z\":0,\"y\":0,\"x\":         


        
10条回答
  •  一生所求
    2020-11-29 04:31

    There are two things you need to do to get this as you want:

    • you need to use something else than a dict, because it doesn't keep the items ordered
    • you need to dump that alternative in the appropriate way.¹

    import sys
    import ruamel.yaml
    from ruamel.yaml.comments import CommentedMap
    
    d = CommentedMap()
    d['z'] = 0
    d['y'] = 0
    d['x'] = 0
    
    ruamel.yaml.round_trip_dump(d, sys.stdout)
    

    output:

    z: 0
    y: 0
    x: 0
    

    ¹ This was done using ruamel.yaml a YAML 1.2 parser, of which I am the author.

提交回复
热议问题