Skip to main content
 首页 » 编程设计

python之输入字典 : values that are lists

2025年05月04日13lhb25

谁能帮我实现这个功能?我不知道写代码,我在函数体中写的是错误的。

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}