python - 创建一个新字典的更简单方法,其中另一个字典的值作为键,出现次数作为值
问题描述
我将首先为我的代码提供一些上下文,而不是进一步解释,这些代码有效但似乎效率很低:
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}
>>> get_quantities({'t1': ['pie'],
't2': ['orange pie'], 't3': ['pie']})
{'pie': 2, 'orange pie': 1}
"""
food_to_quantity = {}
# Accumulate the food information here.
# Creating a dictionary with the new keys as values from the other
for j in table_to_foods.values():
for a in j:
food_to_quantity[a] = 0
# Increment based on number of occurrences
for j in table_to_foods.values():
for a in j:
food_to_quantity[a] += 1
return food_to_quantity
必须有一种更简单的方法来创建一个新字典,其中 table_to_foods 的值作为键,任何食物值的出现次数作为值。
解决方案
这就是我会怎么做。
table_to_foods = {'t1': ['Vegetarian stew', 'Poutine', 'Vegetarian stew'],
't3': ['Steak pie', 'Poutine', 'Vegetarian stew'], 't4': ['Steak pie', 'Steak pie']}
food_to_quantity = {}
for foods in table_to_foods.values():
for food in foods:
if(food not in food_to_quantity):
food_to_quantity[food]=1
else:
food_to_quantity[food]+=1
print(food_to_quantity)
输出:{'素食炖菜':3,'Poutine':2,'牛排馅饼':3}
推荐阅读
- javascript - 根据用户输入对 json 数据进行排序
- java - 将 JScrollPane 添加到由 TableModel 初始化的 JTable 时出现问题
- docker-compose - 无法将消息从 dapr 发布 url 发布到 rabbitmq 交换
- python - So I'm Facing A Issue Here, During Calculating The Data Its Ignoring Decimal And Just Calculating The Integer, 10*11.50 Should Be 115
- python-3.x - IntegrityError:django 中的 FOREIGN KEY 约束失败
- c++ - 没有要调用的匹配函数,使用 std::thread
- javascript - jQuery .find() 找不到
- python - ModuleNotFoundError:没有名为“h2oaicore”的模块
- spring - 根据业务逻辑屏蔽字段值的最佳方法是什么
- razor - 如何在 ASP .NET Core MVC Web 应用程序中制作 .cshtml 弹出窗口