如何只询问python的新键:值对?

时间:2017-07-22 19:57:47

标签: 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字典中。 但是,如果不事先了解新菜肴,我怎样才能完成与新菜肴结果相同的“计数”? 我尝试了各种方法,但在“最佳情况”中,我得到了最后添加的键值对,因为每次迭代都会覆盖变量(这有意义吗?)

我读到关于字典理解的解决方案,但坦率地说,我真的不明白如何在这里使用它。我试图将新的输入不仅添加到字典中,还添加到新的List中,但是不再有任何键值对,所以不能解决。 任何能够遵循我模糊且最容易混淆的请求的人?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

您可以遍历所有客人并将他们的菜肴添加到一组中以获得所有菜肴的完整集合。然后打印每道菜的数量。

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