如何要求python只提供新的键:值对?

2024-10-03 21:26:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我要找的是很难解释的,因此我向您展示了我已经拥有的代码和我要找的输出。我尝试了在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理解作为一种解决方法的文章,但坦率地说,我并不真正理解如何在这里使用它。我尝试将新的输入不仅添加到字典中,还添加到一个新的列表中,但是这样就不会有任何键值对了,所以没有成功。 有谁能听从我含糊不清的要求吗?你知道吗


Tags: or方法answerinputitemprintapplesguests
2条回答

你可以迭代所有的客人,并将他们的菜肴添加到一个集合中,得到一套完整的所有菜肴。然后打印每道菜的数量。你知道吗

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

all_dishes = set()
for guest, dishes in allGuests.items():
    all_dishes.update(dishes.keys())

for dish in all_dishes:
    print(" - " + dish +": " + str(totalBrought(allGuests, dish)))

你想要生成一个新的字典,在那里你总结了所有客人的所有菜肴。你知道吗

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))

相关问题 更多 >