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

时间:2014-01-28 20:45:51

标签: python dictionary

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

摘录自我的代码。我认为你看错了就足够了。

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;

我的错误:

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

关于同一错误,有多个SO条目。但没有与这种字典操作有关。

1 个答案:

答案 0 :(得分:12)

很可能你已经在某个地方的temp_dict中放了unicode字符串:

>>> 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

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

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