Can PyYAML dump dict items in non-alphabetical order?

后端 未结 10 847
一向
一向 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:30

    For Python 3.7+, dicts preserve insertion order. Since PyYAML 5.1.x, you can disable the sorting of keys (#254). Unfortunately, the sorting keys behaviour does still default to True.

    >>> import yaml
    >>> yaml.dump({"b":1, "a": 2})
    'a: 2\nb: 1\n'
    >>> yaml.dump({"b":1, "a": 2}, sort_keys=False)
    'b: 1\na: 2\n'
    

    My project oyaml is a monkeypatch/drop-in replacement for PyYAML. It will preserve dict order by default in all Python versions and PyYAML versions.

    >>> import oyaml as yaml  # pip install oyaml
    >>> yaml.dump({"b":1, "a": 2})
    'b: 1\na: 2\n'
    

    Additionally, it will dump the collections.OrderedDict subclass as normal mappings, rather than Python objects.

    >>> from collections import OrderedDict
    >>> d = OrderedDict([("b", 1), ("a", 2)])
    >>> import yaml
    >>> yaml.dump(d)
    '!!python/object/apply:collections.OrderedDict\n- - - b\n    - 1\n  - - a\n    - 2\n'
    >>> yaml.safe_dump(d)
    RepresenterError: ('cannot represent an object', OrderedDict([('b', 1), ('a', 2)]))
    >>> import oyaml as yaml
    >>> yaml.dump(d)
    'b: 1\na: 2\n'
    >>> yaml.safe_dump(d)
    'b: 1\na: 2\n'
    

提交回复
热议问题