我有这个例子:
import yaml
from collections import OrderedDict
data = [OrderedDict({"one": u"Hello\u2122", "two":["something", u"something2", u"something3"]})]
print yaml.dump(data, default_flow_style=False, default_style='"', allow_unicode=True, encoding="utf-8")
打印出来:
- !!python/object/apply:collections.OrderedDict
- - - "two"
- - "something"
- !!python/unicode "something2"
- !!python/unicode "something3"
- - "one"
- "Hello\u2122"
我使用OrderedDict
因为我想在转储到YML时保留键顺序。但是,在将YML读回python时,我并不关心顺序。
我如何美化转储类似于:
- two:
- "something"
- "something2"
- "something3"
one:
- "Hello\xe2\x84\xa2"
然后使用yaml.load()
将其读回到python ?
答案 0 :(得分:1)
一种选择是使用表示器来更改某些对象的序列化。但这必须根据具体情况进行,我不知道它是否适合您的特定用例。
保留OrderedDict
中的订单会变得更加棘手,因为如果地图具有items
属性,represent_mapping
将始终对项目进行排序,但将项目作为元组应该工作。
import yaml
from yaml.representer import SafeRepresenter
from collections import OrderedDict
data = [OrderedDict({"one": u"Hello\u2122",
"two":["something", u"something2", u"something3"]})]
# Represent an OrderedDict preserving order
def _represent_dict_in_order(dumper, odict):
return dumper.represent_mapping(u'tag:yaml.org,2002:map', odict.items())
# Use a safe dictionary representer for OrderectDict
yaml.add_representer(OrderedDict, _represent_dict_in_order)
# Use a safe string representer for unicode data
yaml.add_representer(unicode, SafeRepresenter.represent_unicode)
print yaml.dump(data, default_flow_style=False,
default_style='"', allow_unicode=True, encoding="utf-8")