【发布时间】:2018-06-22 18:36:30
【问题描述】:
我有一本字典already_eaten,它的键是我的persons 的名字。我想跟踪每个person 吃过的foods:
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.items():# <--
already_ate[person].append(food) # <-- i want to apend food value in person key if person key exist
else: # <-- and if the person is not the key in dictionary then make it a new key assigning the value of food
already_ate[person] = food # <--
else:
print("{} does not ate as we are out of {}".format(person,food))
else:
print("{} are out of stocks".format(food))
【问题讨论】:
-
您可以使用
get来检查该人是否存在,如果不存在则返回None。例如:already_ate.get("person")将获取该人(如果存在)或返回 None
标签: python list dictionary append