我要找的是很难解释的,因此我向您展示了我已经拥有的代码和我要找的输出。我尝试了在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字典中。 但是,我怎么能在事先不知道的情况下,对新菜进行与结果中显示的完全相同的“计数”? 我尝试了各种方法,但在“最佳情况”中,我得到了最后添加的键值对,因为每次迭代都会覆盖变量(这有意义吗??)你知道吗
我读到了关于dict理解作为一种解决方法的文章,但坦率地说,我并不真正理解如何在这里使用它。我尝试将新的输入不仅添加到字典中,还添加到一个新的列表中,但是这样就不会有任何键值对了,所以没有成功。 有谁能听从我含糊不清的要求吗?你知道吗
你可以迭代所有的客人,并将他们的菜肴添加到一个集合中,得到一套完整的所有菜肴。然后打印每道菜的数量。你知道吗
你想要生成一个新的字典,在那里你总结了所有客人的所有菜肴。你知道吗
相关问题 更多 >
编程相关推荐