【发布时间】:2021-10-06 00:52:58
【问题描述】:
我非常接近自动转储从数据框创建的 yml 文件以用于自动化任务。
我有一个结构如下的函数:
def get_all_values(nested_dictionary):
for key,value in nested_dictionary.items():
model = {
"models": [
{
"name": key,
"columns": None
}
]
}
yield(model)
for key,value in value.items():
table = [
{
"name": key,
"tests": [
"not_null",
"unique"
]
}
]
yield(table)
nested_dictionary = d1
get_all_values(nested_dictionary)
data = get_all_values(nested_dictionary)
with open('data.yml', 'w') as outfile:
with redirect_stdout(outfile):
for i in data:
ruamel.yaml.round_trip_dump(i,outfile, indent=5, block_seq_indent=2)
它引用的 dict 作为生成器生成。 dicts结构是:
{'models': [{'name': 'budgets_sales', 'columns': None}]}
[{'name': 'budget_amt', 'tests': ['not_null', 'unique']}]
[{'name': 'budget_group', 'tests': ['not_null', 'unique']}]
[{'name': 'budget_name', 'tests': ['not_null', 'unique']}]
[{'name': 'budget_pk', 'tests': ['not_null', 'unique']}]
这工作“很好”......但输出如下:
models:
- name: budgets_sales
columns:
- name: budget_amt
tests:
- not_null
- unique
- name: budget_group
tests:
- not_null
- unique
- name: budget_name
tests:
- not_null
- unique
我要求字典中键的所有值都有额外的缩进。我不知道如何使值缩进键。
如果正确的话应该是这样的:
- name: budgets_sales
columns:
- name: budget_amt
tests:
- not_null
- unique
- name: budget_group
tests:
- not_null
- unique
- name: budget_name
tests:
- not_null
- unique
- name: budget_pk
tests:
- not_null
- unique
- name: entry_type_code
tests:
- not_null
- unique
- name: institution_fk
tests:
- not_null
- unique
谁能提供一种方法?
感谢 Anthon,这是我最终使用的:
def get_all_values(nested_dictionary):
res = [{"version":2},{"models":None}]
for key,value in nested_dictionary.items():
seq = []
res.append([{"name": key, "columns": seq}])
# for key1, value1 in value.items(): # not using value1
for key1 in value.keys():
elem = {"name": key1, "tests": ["not_null", "unique"]}
seq.append(elem)
return res
nested_dictionary = d1
get_all_values(nested_dictionary)
data = get_all_values(nested_dictionary)
with open('data.yml', 'w') as outfile:
with redirect_stdout(outfile):
for i in data:
yaml = ruamel.yaml.YAML()
yaml.indent(mapping=5, sequence=5, offset=4)
yml.dump(i,outfile)
【问题讨论】:
-
在您生成有效的 .yml 文件后,也许使用 YAML 格式化程序作为最后一步?
-
你好 zr0gravity7。让我试一试。您是在考虑文本编辑器还是 python 中的其他函数?
-
@LewisBaker 我试图更新您的代码和数据(它们都包含无效的 YAML)。我希望能代表您想要的,如果不编辑帖子,请粘贴您的代码,选择它并按 Ctrl+K 缩进整个内容,使其看起来像帖子中的代码/数据。
-
你不能在 5 个位置有 4 个偏移量,元素指示符后面必须有一个空格 (
-),IIRC 偏移量会自动减少
标签: python yaml pyyaml ruamel.yaml