Python 在字典中添加值?
当我尝试在字典中添加值时,似乎出现了一个关键错误,我做错了什么?Python 在字典中添加值?,python,dictionary,Python,Dictionary,当我尝试在字典中添加值时,似乎出现了一个关键错误,我做错了什么?食物数量[食物]还不存在,需要添加1。如果它不存在,您可能希望将1添加到0,但Python并不这样认为 defaultdict救命 def get_quantities(orders): """ (dict of {str: list of str}) -> dict of {str: int} >>> get_quantities({'t1': ['Vegetarian stew', '
食物数量[食物]
还不存在,需要添加1
。如果它不存在,您可能希望将1
添加到0
,但Python并不这样认为
defaultdict
救命
def get_quantities(orders):
""" (dict of {str: list of str}) -> dict of {str: int}
>>> 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_quantity = {}
total = 0
for table in orders:
for food in orders[table]:
food_quantity[food] += 1
return food_quantity
defaultdict(int)
创建一个新的int(值0
)来代替KeyError
s。这适用于查找和扩充分配(+=
)
从:
返回一个新的类似字典的对象。defaultdict是内置dict类的一个子类。它重写一个方法并添加一个可写实例变量。其余的功能与dict类相同,此处不作说明
第一个参数提供默认工厂属性的初始值;默认为“无”。所有剩余参数的处理方式与传递给dict构造函数的方式相同,包括关键字参数
>>> from collections import defaultdict
>>> food_quantity = defaultdict(int)
>>> food_quantity[food] += 1
>>> food_quantity[food]
1