简体   繁体   English

如何通过Python在yaml文件中的一个标签下添加列表

[英]how to add a list under one tag in yaml file by Python

I want to make one YAML file by python like as below. 我想通过python制作一个YAML文件,如下所示。

A:
  B:
    - c: d

but if I do it as follows: 但是如果我这样做如下:

data = {'A':{'B':{'- c':'d'}}}
yaml.dump(data,file,default_flow_style = False)

the output in the file is as below: 文件中的输出如下:

A:
  B:
    '-c': d

How can I get rid of the quotation around the - c ? 如何删除- c周围的引号?

The quotes are there because the - is a reserved word. 出现引号是因为-是保留字。 If you want to make a sequence in YAML you have include a list in Python, and you only have dictionaries (which are output as mappings). 如果要在YAML中创建序列,则必须在Python中包含一个列表,并且只有字典(作为映射输出)。

Try: 尝试:

data = {'A':{'B': [{'c':'d'}]}}
yaml.dump(data, sys.stdout, default_flow_style = False)

which gets you: 这使您:

A:
  B:
  - c: d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM