如何将字典和列表安全转储到 YAML 中? [英] How to safe_dump the dictionary and list into YAML?

查看:25
本文介绍了如何将字典和列表安全转储到 YAML 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望输出为下面的 YAML:

I want the output as the YAML below:

 - item: Food_eat
   Food:
     itemId: 42536216
     category: fruit
     moreInfo:
       - "organic"

我已使用以下代码按与上述相同的顺序打印,但输出未按预期进行.

I have used the following code to print in the same order as above but output is coming not as expected.

代码:

import yaml

yaml_result = [{'item': 'Food_eat', 'Food': {'foodNo': 42536216,'type': 'fruit','moreInfo': ['organic']}}]

print(yaml.safe_dump(yaml_result))
print(yaml_test)

输出:

- Food:
    moreInfo:
    - organic
    category: fruit
    itemId: 42536216
  item: Food_eat

不确定如何获得所需的输出.

Not sure how to get the desired output.

推荐答案

ruamel.yaml(免责声明:我是那个包的作者)确实有此功能是内置的,因为必须支持其功能往返(加载、修改、转储)YAML 数据而不引入虚假数据变化.除此之外,它默认为 YAML 1.2,而 PyYAML 仅支持 YAML 1.1(10 多年前已过时).

ruamel.yaml (disclaimer: I am the author of that package) does have this feature built-in, as it is necessary to support its capability to round-trip (load, modify, dump) YAML data without introducing spurious changes. Apart from that it defaults to YAML 1.2, whereas PyYAML only supports YAML 1.1 (outdated more than 10 years ago).

import sys
import ruamel.yaml

data = [{'item': 'Food_eat', 'Food': {'foodNo': 42536216,'type': 'fruit','moreInfo': ['organic']}}]

yaml = ruamel.yaml.YAML()
yaml.indent(sequence=4, offset=2)
yaml.dump(data, sys.stdout)

给出:

  - item: Food_eat
    Food:
      foodNo: 42536216
      type: fruit
      moreInfo:
        - organic

这依赖于现代 Python 保持字典插入顺序的能力.为了较旧的版本,如 Python 2.7,你必须明确地制作一个对象 CommentedMap(从 ruamel.yaml.comments 和要么给它一个元组列表(按正确的顺序),要么分配按您希望转储的顺序排列键值对.

This relies on a modern Python's ability to keep the insertion ordering of a dict. For older versions, like Python 2.7, you'll have to explicitly make an object CommentedMap (as imported from ruamel.yaml.comments and either give it a list of tuples (in the right order), or assign the key value pairs in the order you want them to be dumped.

正如你在序列的缩进中看到的,破折号有一个偏移量,这是你不重写其发射器就无法使用 PyYAML 实现.

As you can see within the indentation of the sequence the dash has an offset, this is something you cannot achieve using PyYAML without rewriting its emitter.

在 PyYAML 中,您不想将 print(yaml.safe_dump(data)) 作为这对于wrt来说都是低效的.内存和时间,始终使用 yaml.safe_dump(data, sys.stdout) 代替.

Within PyYAML you don't want to do print(yaml.safe_dump(data)) as that is inefficient both wrt. memory and time, always use yaml.safe_dump(data, sys.stdout) instead.

这篇关于如何将字典和列表安全转储到 YAML 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆