Я взял следующий код из книги, но не понял из многочисленных исследований - PullRequest
0 голосов
/ 16 июня 2020

Я взял его из учебника под названием «Автоматизируйте скучную вещь с помощью Python». Я провел много исследований, но все еще не могу понять. Может ли кто-нибудь дать пошаговое разъяснение?

    allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
                'Bob': {'ham sandwiches': 3, 'apples': 2},
                'Carol': {'cups': 3, 'apple pies': 1}}

        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(' - Apples' + str(totalBrought(allGuests, 'apples')))
    print(' - Cups' + str(totalBrought(allGuests, 'cups')))
    print(' - Cakes ' + str(totalBrought(allGuests,'cakes')))
    print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
    print(' - Apple Pies' + str(totalBrought(allGuests,'apple pies')))

Вывод:

Number of things being brought:
- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies
1

1 Ответ

0 голосов
/ 16 июня 2020
# this is dictionary. format is {<key>: <value>},
# in this code it is nested dictionary {<dict1>: {<innerkey>: <value>}}
allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
             'Bob': {'ham sandwiches': 3, 'apples': 2},
             'Carol': {'cups': 3, 'apple pies': 1}}


# in this function you will receive nested dictionary (guests)
# and the value (item) which will be searched as key in dictionary
def totalBrought(guests, item):
    numBrought = 0  # this is return value and set as zero initially
    for k, v in guests.items():  # for loop to iterate each dictionary element and its nested elements, items() will return elements of dictionary
        numBrought = numBrought + v.get(item, 0)  # here you check whether your value is exist in inner dictionary.
                                                  # if so, you will get its value (integer in here) with get() function and sum them continuously
    return numBrought  # and return result


print('Number of things being brought:')
print(' - Apples' + str(totalBrought(allGuests, 'apples')))  # in total you have 7 apples ('apples': 5 + 'apples': 2)
print(' - Cups' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies' + str(totalBrought(allGuests, 'apple pies')))
...