如何从包含 munch 的字典中编写 YAML 而没有“!munch.Munch”?
How can I write YAML from dictionary containing munch without "!munch.Munch"?
当从包含 munch.Munch
的字典写入 yaml 文件时,输出中会出现“!munch.Munch”。我怎样才能避免这种行为?
显示问题的最小示例
data = {"A":"a", "B":munch.Munch({"C":"c"})}
with open("test.yaml", "w") as file:
yaml.dump(data, file)
生产:
A: a
B: !munch.Munch
C: c
但想要的输出是:
A: a
B:
C: c
不可行解
当然可以简单地递归遍历字典并将每个 munch.Munch
转换为字典,但我相信有比这更好的解决方案。将 munch.Munch
直接写入 yaml 文件可以按预期工作,并且 munch.Munch
和 dict 之间的区别非常小 - 必须有更好的方法。有什么想法吗?
如果 munch.Munch
来自 this munch repository, you can use safe_dump
instead of dump
(from the readme)。
data = {"A":"a", "B":munch.Munch({"C":"c"})}
with open("test.yaml", "w") as file:
yaml.safe_dump(data, file)
它产生你想要的:
A: a
B:
C: c
当从包含 munch.Munch
的字典写入 yaml 文件时,输出中会出现“!munch.Munch”。我怎样才能避免这种行为?
显示问题的最小示例
data = {"A":"a", "B":munch.Munch({"C":"c"})}
with open("test.yaml", "w") as file:
yaml.dump(data, file)
生产:
A: a
B: !munch.Munch
C: c
但想要的输出是:
A: a
B:
C: c
不可行解
当然可以简单地递归遍历字典并将每个 munch.Munch
转换为字典,但我相信有比这更好的解决方案。将 munch.Munch
直接写入 yaml 文件可以按预期工作,并且 munch.Munch
和 dict 之间的区别非常小 - 必须有更好的方法。有什么想法吗?
如果 munch.Munch
来自 this munch repository, you can use safe_dump
instead of dump
(from the readme)。
data = {"A":"a", "B":munch.Munch({"C":"c"})}
with open("test.yaml", "w") as file:
yaml.safe_dump(data, file)
它产生你想要的:
A: a
B:
C: c