Controlling Yaml Serialization Order in Python

后端 未结 4 1040
渐次进展
渐次进展 2020-12-15 08:42

How do you control how the order in which PyYaml outputs key/value pairs when serializing a Python dictionary?

I\'m using Yaml as a simple serialization format in a

4条回答
  •  抹茶落季
    2020-12-15 08:45

    The last time I checked, Python's dictionaries weren't ordered. If you really want them to be, I strongly recommend using a list of key/value pairs.

    [
        ('key', 'value'),
        ('key2', 'value2')
    ]
    

    Alternatively, define a list with the keys and put them in the right order.

    keys = ['key1', 'name', 'price', 'key2'];
    for key in keys:
        print obj[key]
    

提交回复
热议问题