PYTHON'Unicode'对象不支持项目分配

时间:2012-05-08 03:49:03

标签: python

需要一些帮助,请注意以下错误:

TypeError :'unicode'对象不支持项目分配

Ligne :menuDic [str(menu.id)] ['menuDishes'] [str(d.dish.dishType.name)] ['dishTypeName'] [str(d.dish。 id)] = {}

def getDishOfTheWeek():
    menuDic = Ddict(dict)
    for menu in Menus.select().where(state = True):
        menuDic[str(menu.id)]={}
        menuDic[str(menu.id)]['menuId']=menu.id
        menuDic[str(menu.id)]['menuName']=menu.name
        menuDic[str(menu.id)]['menuCountry']=menu.country.name
        menuDic[str(menu.id)]['menuDishes']={}
        for d in DishMenuRels.select().where(menu = menu.id).join(Dishes).join(DishTypes).order_by('name')
            menuDic[str(menu.id)]['menuDishes'][str(d.dish.dishType.name)] = {}
            menuDic[str(menu.id)]['menuDishes'][str(d.dish.dishType.name)]['dishTypeName'] = d.dish.dishType.name
            menuDic[str(menu.id)]['menuDishes'][str(d.dish.dishType.name)]['dishTypeName'][str(d.dish.id)] = {}
            menuDic[str(menu.id)]['menuDishes'][str(d.dish.dishType.name)]['dishTypeName'][str(d.dish.id)]['dishId'] = d.dish.id
            menuDic[str(menu.id)]['menuDishes'][str(d.dish.dishType.name)]['dishTypeName'][str(d.dish.id)]['dishState'] = d.dish.name
            menuDic[str(menu.id)]['menuDishes'][str(d.dish.dishType.name)]['dishTypeName'][str(d.dish.id)]['dishType'] = d.dish.price
            menuDic[str(menu.id)]['menuDishes'][str(d.dish.dishType.name)]['dishTypeName'][str(d.dish.id)]['dishName'] = d.dish.country.name
    print json.dumps(menuDic, indent=5, sort_keys=True)

谢谢

1 个答案:

答案 0 :(得分:7)

在这里,您将值d.dish.dishType.name(看似是一个unicode字符串)分配给字典键'dishTypeName'

        menuDic[str(menu.id)]['menuDishes'][str(d.dish.dishType.name)]\
               ['dishTypeName'] = d.dish.dishType.name

然后,您对该值使用项目分配;以下内容与d.dish.dishType.name[str(d.dish.id)] = {}相同。

        menuDic[str(menu.id)]['menuDishes'][str(d.dish.dishType.name)]\
               ['dishTypeName'][str(d.dish.id)] = {}

毋庸置疑,这会导致错误,因为d.dish.dishType.name是一个不可变的字符串。

我可以补充一点,你最好将这些作业分成更小的部分,也许还有一些功能吗?这些冗长的赋值语句 - 我相信你已经注意到了 - 很难解释和调试。