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

如何解决字典键值互换问题?修改赋值语句为何能消除报错?

字典键值互换时AttributeError的原因解析

我想实现字典的键值互换(将原字典的值转为键,键转为值),原字典的键是组名,值是该组下的用户列表,目标是生成以用户为键、该用户所属组名列表为值的新字典。

我尝试的代码如下:

def groups_per_user(group_dictionary):
    user_groups = {}
    # Go through group_dictionary
    for key, value in group_dictionary.items():
        # Now go through the users in the group
        for user in value:
            if user in user_groups:
                user_groups[user].append(key)
            user_groups[user] = key
            # Now add the group to the the list of
# groups for this user, creating the entry
# in the dictionary if necessary

    return(user_groups)

print(groups_per_user({"local": ["admin", "userA"],
        "public":  ["admin", "userB"],
        "administrator": ["admin"] }))

运行后出现如下错误:

Error on line 18:
    "administrator": ["admin"] }))
Error on line 8:
    user_groups[user].append(key)
AttributeError: 'str' object has no attribute 'append'

我发现将代码中的user_groups[user] = key改为user_groups[user] = [key]后,代码就能正常运行且不再报错,想知道这一现象的原因。


问题根源

你遇到的AttributeError是因为字典值的类型错误:

  • 第一次处理某个用户(比如admin)时,由于user_groups里还没有这个用户的键,代码执行user_groups[user] = key,把该用户对应的值设成了字符串(比如"local")。
  • 当这个用户再次出现在其他组(比如public)时,代码进入if分支尝试调用append()方法,但字符串类型没有append()这个方法,所以抛出错误。

修改后正常运行的原因

改成user_groups[user] = [key]后:

  • 第一次处理用户时,会把该用户对应的值初始化为列表类型(比如["local"])。
  • 后续再处理同一用户时,append()方法就能正常工作——因为列表支持append()操作,可以把新的组名添加到列表里,最终每个用户对应的都是自己所属的所有组名的列表,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:54:54