Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在字典中添加值?_Python_Dictionary - Fatal编程技术网

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