Can PyYAML dump dict items in non-alphabetical order?

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

    Building on @orodbhen's answer:

    old_sorted = __builtins__['sorted']
    __builtins__['sorted'] = lambda x: x
    with open(filename, 'w') as outfile:
        yaml.dump(f_json, outfile)
    __builtins['sorted'] = old_sorted
    

    Just replace the built-in function sorted by a lambda identity function while you use yaml.dump.

提交回复
热议问题