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

如何在不覆盖内容的情况下将字典添加到字典中

把多个字典整合到一起的解决办法

先提个关键问题:你给出的期望代码在Python里跑不起来!因为字典是不可哈希的类型,不能直接放进{}定义的集合里,会直接报TypeError: unhashable type: 'dict'错误。所以得换个靠谱的方式来实现“不覆盖内容,把两个字典放到同一个结构里”的需求。

方法1:用列表存多个字典(最常用)

这是最简单也不会出错的方式:

dic1 ={'materials_id': 5, 'name': 'paint', 'capacity': 3}
dic2 ={'materials_id': 4, 'name': 'chemistry', 'capacity': 3}

# 把两个字典放进列表里
data = [dic1, dic2]

运行后得到的结果是:

[{'materials_id': 5, 'name': 'paint', 'capacity': 3}, {'materials_id': 4, 'name': 'chemistry', 'capacity': 3}]

方法2:非要用集合的话(得转格式)

如果你铁了心要用集合,得先把每个字典转成可哈希的类型,比如把字典的键值对转成元组:

dic1 ={'materials_id': 5, 'name': 'paint', 'capacity': 3}
dic2 ={'materials_id': 4, 'name': 'chemistry', 'capacity': 3}

# 转成元组后再放进集合
data = {tuple(dic1.items()), tuple(dic2.items())}

得到的结果是:

{(('materials_id', 5), ('name', 'paint'), ('capacity', 3)), (('materials_id', 4), ('name', 'chemistry'), ('capacity', 3))}

额外说明

你想要的那种直接把字典放进集合的写法不符合Python语法,所以优先用列表来存多个字典,既能保留原字典的完整结构,又能正常使用。

内容的提问来源于stack exchange,提问作者Trần Tiến

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:35:18