def get_quantities(table_to_foods):
""" (dict of {str: list of str}) -> dict of {str: int}
The table_to_foods dict has table names as keys (e.g., '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 table_to_foods 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_to_quantity = {}
# Accumulate the food information here.
return food_to_quantity
私は何もインポートできません(コレクション/チェーン)。私は以下で試した2つの選択肢がありますが、どちらも失敗しました。Python:各キーが食べ物であり、各値が注文された食べ物の量である辞書を返す方法?
これは、プログラムの時間を作る:
for table in table_to_foods:
count = 0
while count < len(table):
for food in table[count]:
if food in food_to_quantity:
food_to_quantity[food] += 1
else:
food_to_quantity[food] = 1
count += 1
これははAttributeErrorを取得します。
for table_order in table_to_foods.itervalues():
for menu_item in table_order:
if menu_item in food_to_quantity:
food_to_quantity[menu_item] += 1
else:
food_to_quantity[menu_item] = 1
はどうもありがとうございます動作します!私はitervaluesを値に変更すると、これは完璧に機能しました:)私はあなたが私に事を説明する時間を費やしてくれて、私は十分な評判を持っていないために表示されませんが、あなたをアップしました – Ama