早教吧 育儿知识 作业答案 考试题库 百科 知识分享

python问题defgetquantities(orders):"""(dictof{str:listofstr})->dictof{str:int}Theordersdicthastablenamesaskeys('t1','t2',andsoon)andeachvalueisalistoffoodsorderedforthattable.Returnadictionarywhereeachkeyisaf

题目详情
python问题
def get_quantities(orders):
""" (dict of {str:list of str}) -> dict of {str:int}
The orders dict has table names as keys ('t1','t2',and so on) and each value
is a list of foods ordered for that table.
Return a dictionary where each key is a food from orders and each
value is the quantity of that food that was ordered.
>>> get_quantities({'t1':['Vegetarian stew','Poutine','Vegetarian stew'],'t3':['Steak pie','Poutine','Vegetarian stew'],'t4':['Steak pie','Steak pie']})
{'Vegetarian stew':3,'Poutine':2,'Steak pie':3}
"""
food_sums = {}
# Accumulate the food information here.
return food_sums
▼优质解答
答案和解析
def get_quantities(orders):
    """  (dict of {str: list of str}) -> dict of {str: int}

    The orders dict has table names as keys ('t1', 't2', and so on) and each value
    is a list of foods ordered for that table.

    Return a dictionary where each key is a food from orders and each
    value is the quantity of that food that was ordered.

    >>> get_quantities({'t1': ['Vegetarian stew', 'Poutine', 'Vegetarian stew'], 't3': ['Steak pie', 'Poutine', 'Vegetarian stew'], 't4': ['Steak pie', 'Steak pie']})
    {'Vegetarian stew': 3, 'Poutine': 2, 'Steak pie': 3}    
    """

    food_sums = {}
    # Accumulate the food information here.
    for tb, foods in orders.iteritems():
        for food in foods:
            food_sums[food] = food_sums.get(food, 0) + 1

    return food_sums