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

如何在Python字典中设置data_providers列表并修复TypeError错误

问题解决:TypeError: unhashable type: 'dict'

你的代码报错核心原因是错误地用大括号{}定义了data_providers的取值:

  • 大括号在Python中会被解析为集合(set),而集合要求元素必须是可哈希类型,字典(dict)属于不可哈希类型,因此触发TypeError。
  • 你实际需要的是列表(对应JSON中的数组结构),必须用方括号[]来定义。

修正后的代码如下:

# 确保owner_name、owner_url、owner_api_url已从API响应中获取
output_dict = {
    'data_providers': [
        {
            'name': 'NBN Atlas',
            'url': 'https://registry.nbnatlas.org/datasets',
            'api_url': 'https://registry.nbnatlas.org/ws/dataResource',
        },
        {
            'name': owner_name,
            'url': owner_url,
            'api_url': owner_api_url,
        },
    ]
}

# 若要生成你期望的外层数组结构,将字典包裹进列表
final_output = [output_dict]

如果需要将结果转存为JSON文件,可使用以下代码:

import json

with open('result.json', 'w', encoding='utf-8') as f:
    json.dump(final_output, f, indent=2)

执行后生成的JSON文件结构将完全符合你的预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:10:02