谁能帮我这个功能?我没有编写代码的线索,我在函数体内编写的内容是错误的。
def get_quantities(table_to_foods: Dict[str, List[str]]) -> Dict[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 = {}
for t in table_to_foods:
for i in table_to_foods[t]:
if i in table_to_foods[t]:
food_to_quantity[i] = food_to_quantity[i] + 1
return food_to_quantity
最佳答案
如果您喜欢使用itertools.chain
和collections.Counter
的另一种方法:
from itertools import chain
from collections import Counter
dict(Counter(chain.from_iterable(foods.values())))
#or Simply
dict(Counter(chain(*foods.values())))
#Output:
#{'apple': 3, 'banana': 4, 'grapes': 1, 'orange': 1}
关于python - 输入dict:列出的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47106751/