简体   繁体   中英

Printing Total Values in Dictionary

I am a begginer pythonista and currently following a guide here . I am looking at a piece of code in Chapter 5 in a section called Nested Dictionaries and Lists. I have cut some things from the code and it is displayed below:

allGuests = {'Carol': {'cups': 3, 'apple pies': 1}, 'Tom': {'cups': 4, 'juice': 4}}

def totalBrought(guests, item):
    numBrought = 0
    for k, v in guests.items():
        numBrought = numBrought + v.get(item, 0)
        return numBrought

print('Number of things being brought:')
print(' - Cups being brought ' + str(totalBrought(allGuests, 'cups')))

Below is the output of the above code:

Number of things being brought:
 - Cups being brought 3

Process finished with exit code 0

What the above code should accomplish is to print out the total number of cups that Carol and Tom are bringing. Instead, it prints out only the cups that Carol is bringing. The expected output should be like below:

Number of things being brought:
 - Cups being brought 7

Process finished with exit code 0

I have a looked at an example here and tried it myself but it isn't what I need. I'm trying to understand the issue with the code and how to properly output the total values, that are the same, within a nested dictionary.

The issue is with the indentation of return statement:

allGuests = {'Carol': {'cups': 3, 'apple pies': 1}, 'Tom': {'cups': 4, 'juice': 4}}

def totalBrought(guests, item):
    numBrought = 0
    for k, v in guests.items():
        numBrought = numBrought + v.get(item, 0)
    return numBrought

print('Number of things being brought:')
print(' - Cups being brought ' + str(totalBrought(allGuests, 'cups')))

Output:

Number of things being brought:
 - Cups being brought 7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM