如何在Python字典中为已存在键追加列表值,不存在则新建键?
修正你的
enter_purchase函数逻辑问题 我看到你的代码里有两个关键问题,导致无法实现预期的跟踪功能,咱们一个个拆解解决:
1. 错误的用户存在性判断
你用if person in already_ate.items()来检查用户是否在字典中,但items()返回的是字典的键值对元组集合(比如[("Alice", ["apple"]), ("Bob", ["banana"])]),直接判断person是否在里面完全不对。正确的做法是直接检查person是否是字典的键,也就是if person in already_ate。
2. 新建用户时错误的赋值类型
当用户不在字典里时,你写了already_ate[person] = food,这会把对应的值设成单个字符串,但我们需要的是列表类型(方便后续追加食物),所以应该改成already_ate[person] = [food],把food放到列表里作为初始元素。
修正后的完整代码
def enter_purchase(): food = input("What food was eaten : ") person = input("Who ate the food? ") if food in stock: if stock[food] > 0 : stock[food] -= 1 # 修正:检查用户是否为字典的键 if person in already_ate: already_ate[person].append(food) else: # 修正:初始化为包含当前食物的列表 already_ate[person] = [food] else: print("{} cannot eat as we are out of {}".format(person, food)) else: print("{} is out of stock".format(food))
另外顺手调整了两处语法小问题:把does not ate改成cannot eat,are out of stocks改成is out of stock,让提示语句更通顺自然~
内容的提问来源于stack exchange,提问作者Kunaal Dhawan
相关产品推荐
相关产品推荐

