python - 更新字典中值的最佳方法
问题描述
我有一个包含参数的字典。我想考虑任何未指定的参数都应该读为零。我看到了几种方法,想知道推荐哪一种:
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 还是其他?
解决方案
这是 的典型用法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}
推荐阅读
- r - 无法基于另一列 R Shiny 在数据框中创建新列
- python - 有没有更好的方法在数据类的列表中提供大量参数?
- webpack - webpack 热中间件:在哪里设置 __resourceQuery?
- c# - 为什么在第一次输出后控制台冻结输出?
- javascript - Nuxt.js:@pivale/nuxt-image-loader-module 不以图像样式创建图像
- c# - 悬停 UWP 时更改按钮颜色
- google-cloud-platform - 我的 GCP 虚拟机服务器使用外部 IP 地址,但不是来自域
- python - 为什么 set(array) 比 array.sort() 快
- kubernetes - K8 - 是否可以在不执行的情况下访问容器的底层卷?
- nuxt.js - 如何避免 BootstrapVue 覆盖 css?