首页 > 解决方案 > 更新字典中值的最佳方法

问题描述

我有一个包含参数的字典。我想考虑任何未指定的参数都应该读为零。我看到了几种方法,想知道推荐哪一种:

parameters = {
    "apples": 2
}

def gain_fruits0 (quantity, fruit):
    if not fruit in parameters :
        parameters[fruit] = 0
    parameters[fruit] += quantity

def gain_fruits1 (quantity, fruits):
    parameters[fruit] = quantity + parameters.get(fruit,0)

参数实际上比这大得多,如果这对于优化目的很重要的话。

那么,最好的方法是什么?gain_fruits0、gain_fruits1 还是其他?

标签: pythondictionary

解决方案


这是 的典型用法defaultdict,它的工作原理与普通字典完全一样,只是它具有您内置的功能:

>>> from collections import defaultdict
>>> d = defaultdict(int)  # specify default value `int()`, which is 0
>>> d['apples'] += 1
>>> d
defaultdict(int, {'apples': 1})
>>> d['apples']  # can index normally
1
>>> d['oranges']  # missing keys map to the default value
0
>>> dict(d)  # can also cast to regular dict
{'apples': 1, 'oranges': 0}

推荐阅读