我的问题非常简单。我有一个自定义顺序的OrderredDict对象,我想将其转换为yaml格式。但似乎yaml.dump无法将Orderredict作为输入。有谁知道怎么做?
答案 0 :(得分:4)
看起来你想要this solution,这会增加一个"代表"到YAML。
假设您有一个由嵌套列表,dicts和/或OrderedDicts组成的对象my_object
...如果添加以下行,您可以将其转储到YAML:
yaml.add_representer(OrderedDict, lambda dumper, data: dumper.represent_mapping('tag:yaml.org,2002:map', data.items()))
output = yaml.dump(my_object)
我还发现有必要将我的元组转换为列表:
yaml.add_representer(tuple, lambda dumper, data: dumper.represent_sequence('tag:yaml.org,2002:seq', data))
答案 1 :(得分:0)
也许这就是你需要的东西?
import yaml
from collections import OrderedDict
def dump_ordered_yaml(ordered_data, output_filename, Dumper=yaml.Dumper):
class OrderedDumper(Dumper):
pass
class UnsortableList(list):
def sort(self, *args, **kwargs):
pass
class UnsortableOrderedDict(OrderedDict):
def items(self, *args, **kwargs):
return UnsortableList(OrderedDict.items(self, *args, **kwargs))
OrderedDumper.add_representer(UnsortableOrderedDict, yaml.representer.SafeRepresenter.represent_dict)
with open(output_filename, "w") as f:
yaml.dump(ordered_data, f, Dumper=OrderedDumper)
用法:
a = OrderedDict([('x', 11), ('y', 22)])
dump_ordered_yaml(a, "/tmp/ordered.yaml")
来自终端的结果:
cat /tmp/ordered.yaml
!!python/object/apply:collections.OrderedDict
- - [x, 11]
- [y, 22]
答案 2 :(得分:0)
新解决方案(自 2020 和PyYAML 5.1起)
只需使用
,就可以按其当前顺序转储字典或OrderedDict
yaml.dump(data, default_flow_style=False, sort_keys=False)