python - 如何仅向 python 询问新 key :value pairs?

标签 python dictionary

我正在寻找的内容很难解释,因此我向您展示我已有的代码和我正在寻找的输出。我尝试了在 stackoverflow 中找到的各种方法,但据我判断,没有一个解决方案适用于我的情况。

allGuests = {"Alice": {"apples": 5, "pretzels": 12}, "Bob": {"ham 
             sandwiches": 3, "apples": 2}, "Carol": {"cups": 3, "apple pies": 3}}
def totalBrought(guests, item): 
    numBrought = 0              
    for k, v in guests.items():                             
        numBrought = numBrought + v.get(item, 0) 
    return numBrought
while True:
    print("Is there another Guest coming?")
    answer = input()  
    if (answer == "Yes") or (answer == "yes"):
        newdishesDic = {}
        print("Who is it? ")
        newguest = input() 
        while True:
            print("What does " + newguest + " bring to the picnic?")
            newdish = input()
            print("How much of it?")
            newquantity = input()
            newdishesDic[newdish] = int(newquantity)
            allGuests[newguest] = newdishesDic
            print("Anything else?")
            answer2 = input()
            if (answer2 == "") or (answer2 == "no") or (answer2 == "No"):
                break
            elif (answer2 == "Yes") or (answer2 == "yes"):
                continue
    elif (answer == "") or (answer == "no") or (answer == "No"):
        break
print(" - Apples: " + str(totalBrought(allGuests, "apples")))
print(" - Pretzels: " + str(totalBrought(allGuests, "pretzels")))
....

等等。结果如下:

- Apples: 7
- Pretzels: 12
- Cups: 3
...

如您所见,我添加了新的客人、菜肴和数量,并将这些添加到现有的 allGuests 字典中。 但是,在事先不知道新菜肴的情况下,我如何才能对结果中所示的内容进行完全相同的“计数”呢? 我尝试了各种方法,但在“最好的情况”下,我得到了最后添加的键值对,因为每次迭代都会覆盖变量(这有意义吗?)

我读到了关于字典理解作为解决方案的内容,但坦率地说,我并不太明白如何在这里使用它。我尝试不仅将新输入添加到字典中,还尝试将新输入添加到新列表中,但随后将不再有任何键值对,因此无法解决问题。 谁能遵循我模糊且最可能令人困惑的请求?

最佳答案

您想要生成一个新字典,在其中总结所有客人的所有菜肴。

from collections import defaultdict

def sum_up_all_dishes(all_guests):
    dishes = defaultdict(int)
    for dish in all_guests.values():
        for name, amount in dish:
            dishes[name] += amount
    return dishes

all_guests = {
    "Alice": {"apples": 5, "pretzels": 12}, 
    "Bob": {"ham sandwiches": 3, "apples": 2},
    "Carol": {"cups": 3, "apple pies": 3}
}

while True:
    print("Is there another Guest coming?")
    answer = input()  
    if answer.lower() == "yes":
        newdishesDic = {}
        print("Who is it? ")
        newguest = input() 
        while True:
            print("What does {} bring to the picnic?".format(newguest))
            newdish = input()
            print("How much of it?")
            newquantity = input()
            newdishesDic[newdish] = int(newquantity)
            print("Anything else?")
            answer2 = input()
            if answer2.lower() in ("", "no"):
                break
        all_guests[newguest] = newdishesDic
    else:
        break
all_dishes = sum_up_all_dishes(all_guests)
for name, amount in dishes.items():
    print(" - {}: {}".format(name, amount))

关于python - 如何仅向 python 询问新 key :value pairs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45258633/

相关文章:

string - 附加来自 GO MAP 的关键数据

python - 确定掷骰子是否包含某些组合?

python - 计算字典内嵌套列表中的值的数量

java - 如何使列表在清除后仍包含其元素?

Python - Altair - 带选择的堆积条形图

python - 在 wxPython 中跨面板拖放图像

python - twoSum 找到所有可能的唯一对

python - 如何在 Pandas 数据框中将单元格设置为 NaN

python - 保存图像时 PIL 中的 "SystemError: tile cannot extend outside image"

c# - EditorTemplate 中的 MVC 字典