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

Python字典键值交换报错:'str'对象无append属性

解决字典键值交换时的AttributeError问题

你的代码报错原因很明确:第一次遇到某个值v时,你把dict1[v]赋值成了字符串类型的k,后续再碰到相同的v,试图调用append()方法时,字符串没有这个属性,自然会报错。

修正方案1:统一用列表存储(简单直接)

如果可以接受所有值都是列表(哪怕只有一个元素),直接修改首次赋值的逻辑:

def dict_reverser(dict1, dict2):
    for k, v in dict2.items():
        if v in dict1:
            dict1[v].append(k)
        else:
            # 首次存入就用列表包裹
            dict1[v] = [k]

    print(dict1)

exampleDict = {"Ice": "Cream", "Age": "21", "Light": "Cream", "Double": "Cream"}
myDict = {}

dict_reverser(myDict, exampleDict)

运行结果:{'Cream': ['Ice', 'Light', 'Double'], '21': ['Age']}

修正方案2:实现单个值为字符串、多个值为列表的效果

如果要严格匹配你期望的输出格式,需要在遍历完成后再做一次类型转换:

def dict_reverser(dict1, dict2):
    for k, v in dict2.items():
        if v in dict1:
            dict1[v].append(k)
        else:
            dict1[v] = [k]
    # 遍历处理,把长度为1的列表转为字符串
    for key in list(dict1.keys()):
        if len(dict1[key]) == 1:
            dict1[key] = dict1[key][0]
    print(dict1)

exampleDict = {"Ice": "Cream", "Age": "21", "Light": "Cream", "Double": "Cream"}
myDict = {}

dict_reverser(myDict, exampleDict)

运行结果:{'Cream': ['Ice', 'Light', 'Double'], '21': 'Age'}

补充说明

你之前尝试的dict[v] += k本质是字符串拼接,比如"Ice" + "Light"会变成"IceLight",这显然不是你要的多键对应同一个值的存储方式,所以必须用列表来收集多个键。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 14:13:11