【问题标题】:Need to omit values from yaml output when using defaultdict使用 defaultdict 时需要从 yaml 输出中省略值
【发布时间】:2013-10-11 15:24:11
【问题描述】:

以下代码sn-p:

import yaml
import collections

def hasher():
  return collections.defaultdict(hasher)

data = hasher()

data['this']['is']['me'] = 'test'

print yaml.dump(data)

这会返回:

!!python/object/apply:collections.defaultdict
args: [&id001 !!python/name:__main__.hasher '']
dictitems:
  this: !!python/object/apply:collections.defaultdict
    args: [*id001]
    dictitems:
      is: !!python/object/apply:collections.defaultdict
        args: [*id001]
        dictitems: {me: test}

我将如何删除:

!!python/object/apply:collections.defaultdict
[*id001]

最终目标是:

  this: 
    is: 
      me: "test"

任何帮助表示赞赏!

【问题讨论】:

    标签: python dictionary yaml


    【解决方案1】:

    您需要向yaml 模块注册一个代表:

    from yaml.representer import Representer
    yaml.add_representer(collections.defaultdict, Representer.represent_dict)
    

    现在yaml.dump() 会将defaultdict 对象视为dict 对象:

    >>> print yaml.dump(data)
    this:
      is: {me: test}
    
    >>> print yaml.dump(data, default_flow_style=False)
    this:
      is:
        me: test
    

    【讨论】:

      猜你喜欢
      • 2013-03-13
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多