python - 使用 defaultdict 时需要从 yaml 输出中省略值

标签 python dictionary yaml

以下代码片段:

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"

感谢任何帮助!

最佳答案

您需要向 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

关于python - 使用 defaultdict 时需要从 yaml 输出中省略值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19321776/

相关文章:

python-3.x - python yaml更新保留顺序和注释

amazon-web-services - 如何将我的 AWS Managed AD 链接到 cloudformation 中的 FSx 资源?

python - YAML 列表 -> Python 生成器?

java - 如何在不编写已经很简单的方法的情况下简化类?

python - Pandas:根据条件增加列中的值

python - 我可以比较两个顺序不同的字典的键吗?

具有相同键类型和不同项目类型的c++映射

python - Django 查询集 : filter by 'value LIKE column'

python - 虚拟环境 gcc 错误

python - Python 的 dict.pop 是原子的吗?