2

需要一些帮助来解决这个错误:

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

语言: 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)

谢谢

4

1 回答 1

7

在这里,您将 value d.dish.dishType.name(似乎是一个 unicode 字符串)分配给字典 key '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它是一个不可变的字符串。

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

于 2012-05-08T04:00:33.637 回答