Python 字典中的“TypeError: 'unicode' 对象不支持项目分配”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21416460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:48:07  来源:igfitidea点击:

"TypeError: 'unicode' object does not support item assignment" in dictionaries

pythondictionary

提问by Aidis

I am trying to build/update a dictionary. I have nicknames as keys in temp_dict and looking for ids to add.

我正在尝试构建/更新字典。我有昵称作为 temp_dict 中的键并寻找要添加的 ID。

Excerpt form my code. I think it is enough for you to see my mistake.

摘录我的代码。我想你看到我的错误就足够了。

d1 = {u'status': u'ok', u'count': 1, u'data': [{u'nickname': u'45sss', u'account_id': 553472}]}


   temp_dict = {}
   for key, value in d1.iteritems():
        if "data" == key:
            for dic2 in value:
                  x = dic2['nickname']
                  y = dic2['account_id']
                  temp_dict[x] = y;

My error:

我的错误:

Traceback (most recent call last):
File "untitled.py", line 36, in <module>
get_PlayerIds_Names_WowpApi_TJ_() #Easy going. Some issues with case letters.
File "g:\Desktop\Programming\WOWP API\functions.py", line 44, in get_PlayerIds_Names_WowpApi_TJ_
check_missing_player_ids(basket)
File "g:\Desktop\Programming\WOWP API\functions.py", line 195, in check_missing_player_ids
temp_dict[x] = y;
TypeError: 'unicode' object does not support item assignment

There are multiple SO entries regarding the same error. But no are connected to such dictionary manipulation.

有多个关于同一错误的 SO 条目。但是没有连接到这样的字典操作。

采纳答案by ndpu

Most likely you have put unicode string in temp_dict somewhere:

很可能您已将 unicode 字符串放在 temp_dict 某处:

>>> temp_dict = u''
>>> dic2 = {u'nickname': u'45sss', u'account_id': 553472}
>>> x = dic2['nickname']
>>> y = dic2['account_id']
>>> temp_dict[x] = y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'unicode' object does not support item assignment

init it with empty dict and all will work:

用空字典初始化它,一切都会起作用:

>>> temp_dict = {}
>>> temp_dict[x] = y
>>> temp_dict
{u'45sss': 553472}