将字典转换并写入 YAML 格式
我正在从数据库中检索每个表中所有列的名称,并创建一个字典,其中表名称是键,值是该表中的列名称列表。
my_dict = {
'table_1': ['col_1', 'col_2', 'col_3', 'col_4']
}
我正在尝试将上述字典转换并写入 .yml
文件中的 YAML 格式
我希望 YAML 文件中的输出如下:
tables:
- name: table_1
columns:
- name: col_1
- name: col_2
- name: col_3
- name: col_4
我的尝试:
import yaml
import ruamel.yaml as yml
def to_yaml():
my_dict = {
'table_1' : ['col_1', 'col_2', 'col_3', 'col_4']
}
my_file_path = "/Users/Desktop/python/tables_file"
with open(f"{my_file_path}/structure.yml", "w") as file:
yaml.dump(yaml.load(my_dict), default_flow_style=False)
if __name__ == '__main__'
to_yaml()
上面的代码没有给出预期的输出。我还根据一些与 YAML 相关的 Stack Overflow 帖子尝试了不同的方法,但无法正常工作。
I'm retrieving the names of all the columns in each table from a database and create a dictionary where table name is the key and value is a list of column names in that table.
my_dict = {
'table_1': ['col_1', 'col_2', 'col_3', 'col_4']
}
I'm trying to convert and write the above dictionary into YAML format in a .yml
file
I want my output in YAML file to be as:
tables:
- name: table_1
columns:
- name: col_1
- name: col_2
- name: col_3
- name: col_4
My try:
import yaml
import ruamel.yaml as yml
def to_yaml():
my_dict = {
'table_1' : ['col_1', 'col_2', 'col_3', 'col_4']
}
my_file_path = "/Users/Desktop/python/tables_file"
with open(f"{my_file_path}/structure.yml", "w") as file:
yaml.dump(yaml.load(my_dict), default_flow_style=False)
if __name__ == '__main__'
to_yaml()
The above code didn't give the expected output. I also tried different approaches based on some YAML related Stack Overflow posts but couldn't get it work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用:
struct.yml
的内容:如果你想要预期的输出,你需要改变你的字典的结构。这里没有什么神奇的。
Use:
Content of
structure.yml
:If you want your expected output, you need to change the structure of your dict. There is nothing magical here.