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

Python报错AttributeError: 'dict' object has no attribute 'append'如何解决

错误原因

你定义的restaurants为字典(dict)类型,append()是列表(list)专属的添加元素方法,字典类型不支持该方法,因此运行时抛出AttributeError。

修复方案

参考你预置初始餐厅数据的字典赋值逻辑,将添加分支下的restaurants.append(x)替换为如下代码即可:

restaurants[name] = x
可选优化

为了避免同名餐厅重复录入覆盖已有数据,可以新增存在性校验逻辑,完整的添加分支代码如下:

elif choice == "2":
    name = input("Enter restaurant name: ")
    if name in restaurants:
        print(f"名为 {name} 的餐厅已存在,请勿重复录入")
        continue
    website = input("Enter website: ")
    cuisine = input("Enter cuisine: ")
    new_restaurant = Restaurant(name, website, cuisine)
    restaurants[name] = new_restaurant
    print("餐厅添加成功")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:54:04