You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何强制pyyaml加载包含复杂键的映射?

能否强制PyYAML加载含复杂键的映射?

可以实现,但默认情况下PyYAML会报错——因为Python的普通dict不可哈希,无法作为另一个字典的键。要加载这类结构,需要通过自定义构造器替换默认的映射解析逻辑,具体步骤如下:

1. 定义可哈希的字典类

创建一个继承自dict的子类,实现__hash__方法,让它具备可哈希特性:

class HashableDict(dict):
    def __hash__(self):
        # 将字典项转为有序元组计算哈希,确保相同内容的实例哈希值一致
        return hash(tuple(sorted(self.items())))

2. 注册自定义构造器

告诉PyYAML用自定义类解析YAML中的映射节点:

import yaml

def hashable_dict_constructor(loader, node):
    return HashableDict(loader.construct_mapping(node))

yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, hashable_dict_constructor)

3. 加载目标YAML

现在就能正常解析包含复杂键的结构了:

yaml_content = """
foo:
- {bar: test}: 123
"""
result = yaml.load(yaml_content, Loader=yaml.FullLoader)
print(result)
# 输出示例: {'foo': [{HashableDict({'bar': 'test'}): 123}]}

额外注意事项

如果需要将加载后的数据重新dump回YAML,还得注册自定义代表器,避免输出类名等冗余信息:

def hashable_dict_representer(dumper, data):
    return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data)

yaml.add_representer(HashableDict, hashable_dict_representer)

内容的提问来源于stack exchange,提问作者majkrzak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 14:05:30