Section #6 Solutions
Dictionary Review
>>> classes = {'CS106A': 5, 'PSYCH1': 5, 'PWR1': 4}
>>>
>>> classes['PSYCH1'] # Access the value for the key 'PSYCH1'
5
>>>
>>> classes['CS106A'] = 3 # Update the value for the key 'CS106A', changing it from 5 to 3.
>>> classes
{'CS106A': 3, 'PSYCH1': 5, 'PWR1': 4}
>>>
>>> classes['AMSTUD107'] = 4 # Add a new key/value pair to the dictionary, 'AMSTUD107' with value 4.
>>> classes
{'CS106A': 3, 'PSYCH1': 5, 'PWR1': 4, 'AMSTUD107': 4}
Grocery Lists Dictionaries
def add_item(groceries, store, item, num):
"""
Given a groceries dict which may
already contain some data, update the
dict to add new data for the given
store, item, and num of that item.
>>> add_item({}, 'safeway', 'eggs', 1) # new store, new item
{'safeway': {'eggs': 1}}
>>> add_item({'safeway': {'eggs': 1}}, 'costco', 'croissant', 12) # new store, new item
{'safeway': {'eggs': 1}, 'costco': {'croissant': 12}}
>>> add_item({'safeway': {'eggs': 1}, 'costco': {'croissant': 12}}, 'safeway', 'eggs', 2) # seen store, seen item
{'safeway': {'eggs': 3}, 'costco': {'croissant': 12}}
>>> add_item({'safeway': {'eggs': 3}, 'costco': {'croissant': 12}}, 'safeway', 'coconut milk', 3) # seen store, new item
{'safeway': {'eggs': 3, 'coconut milk': 3}, 'costco': {'croissant': 12}}
"""
if store not in groceries:
groceries[store] = {}
inner = groceries[store]
if item not in inner:
inner[item] = 0
inner[item] += num
'''
can also do:
if item not in inner:
inner[item] = num
else:
inner[item] += num
'''
return groceries
def make_groceries(filename):
"""
Given a grocery list file, where each
line is in the format 'store:item,num'
create and return the groceries dict
made from this list.
Hint: Use your helper function!
>>> make_groceries('short-list.txt')
{'safeway': {'eggs': 3, 'coconut milk': 3}, 'costco': {'croissant': 12}}
"""
groceries = {}
with open(filename) as f:
for line in f:
line = line.strip()
colon = line.find(':')
comma = line.find(',')
store = line[:colon]
item = line[colon + 1:comma]
num = int(line[comma + 1:])
add_item(groceries, store, item, num)
return groceries
def print_groceries(groceries):
"""
(provided)
Prints contents of groceries dict.
"""
for store in groceries:
items = groceries[store]
for item in items:
count = items[item]
print('You need ' + str(count) + ' ' + item + '(s) from ' + store)
def main():
args = sys.argv[1:]
# to run from terminal:
# python3 groceries.py filename # prints out all groceries
if len(args) == 1:
groceries = make_groceries(args[0])
print_groceries(groceries)
if __name__ == '__main__':
main()