我正在從資料庫中檢索每個表中所有列的名稱,并創建一個字典,其中表名是鍵,值是該表中的列名串列。
my_dict = {
'table_1': ['col_1', 'col_2', 'col_3', 'col_4']
}
我正在嘗試將上述字典轉換并寫入檔案中的 YAML.yml格式
我希望我在 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 帖子嘗試了不同的方法,但無法正常作業。
uj5u.com熱心網友回復:
采用:
import yaml
import ruamel.yaml
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 need a dict and a file handler as parameter
yaml = ruamel.yaml.YAML()
yaml.indent(sequence=4, offset=2)
yaml.dump(my_dict, file)
if __name__ == '__main__':
to_yaml()
內容structure.yml:
table_1:
- col_1
- col_2
- col_3
- col_4
如果您想要預期的輸出,則需要更改 dict 的結構。這里沒有什么神奇的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/434464.html
標籤:Python python-3.x 字典 pyyaml
上一篇:如何將JSON物件轉換為字典?
下一篇:遍歷目錄并將檔案名添加到字典
