【问题标题】:Append to or create a list that is a value in a dictionary追加或创建作为字典中值的列表
【发布时间】: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


【解决方案1】:

似乎if person in already_ate.items():# &lt;-- 总是返回False,因为already_ate.items() 返回的是already_ate 的键和值,而不是键。

请改用already_ate.keys()。它只会返回密钥。

另外,already_ate 的键值应该是一个列表。

already_ate = {'Jo' : ['Ice']} #The value of all keys should be a list
stock = {'Rice' : 9}

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.keys(): #.items() to .keys()
            already_ate[person].append(food)
        else:
            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))

【讨论】:

    【解决方案2】:

    如果我正确理解你想要做什么,你想让already_ate 跟踪person 吃过的所有食物。看起来您的数据结构不适合这项工作。

    您需要更改代码以将already_ate[person] 处理为列表,而不是单个字符串:

    if person in already_ate:
        if not food in already_ate[person]:
            already_ate[person].append(food)
    else:
        already_ate[person] = [food]
    

    else 部分会将person 键添加到您的already_ate 字典中,并以吃掉的food 开始列表。

    这样,您可以让每个person 吃掉多个food,但不会有任何给定的food 出现在person 的列表中超过一次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多