【发布时间】:2021-10-25 17:33:08
【问题描述】:
假设我有一个这样的字符串列表:
strings = ["foo.bar.1", "foo.bar.2", "foo.bar.A.1", "foo.bar.A.2"]
我想创建一个这样的 YAML 输出:
foo:
- bar:
- 1
- 2
- A:
- 1
- 2
Python 字典似乎很好地映射到任务,所以我尝试了类似这样的方法,它接受一个点分隔的字符串并返回一个嵌套字典:
def dot_string_to_dictionary(dot_string):
dictionary = {}
split_string = dot_string.split(".")
current_dictionary = dictionary
for part in split_string:
current_dictionary[part] = {}
current_dictionary = current_dictionary[part]
return dictionary
我正在考虑每个字符串,我可以通过这个函数运行它来获取字典。然后,我可以用这个新字典更新一些全局/主字典。最后,我可以将主字典写入 YAML。
【问题讨论】:
-
这是您想要的确切 YAML,还是类似的东西?您的函数不会生成相应的数据结构,即
{'foo': [{'bar': [1, 2, {'A': [1, 2]}]}]}。
标签: python json python-3.x dictionary yaml