python - 在 python 中,是否可以使用单个命令更新或初始化字典键?

标签 python dictionary

例如,假设我想构建一个直方图,我会这样做:

hist = {}
for entry in data:
    if entry["location"] in hist:
        hist[entry["location"]] += 1
    else:
        hist[entry["location"]] = 1

有没有办法避免存在性检查并根据其存在性初始化或更新 key ?

最佳答案

你想要的是一个defaultdict:

from collections import defaultdict
hist = defaultdict(int)
for entry in data:
    hist[entry["location"]] += 1

defaultdict 默认构造字典中尚不存在的任何条目,因此对于整数,它们从 0 开始,您只需为每个项目添加一个。

关于python - 在 python 中,是否可以使用单个命令更新或初始化字典键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7280644/

相关文章:

python - 使用 pip 从 PyPi 镜像安装 IPython

java - 如何使用 map 创建类对象的副本?

python:用另一个列表中的项目替换列表中的项目

ios - 检查 nil 并快速从字典中提取数据

python - 标准化 scipy.ndimage.filters.correlate

Python:如何处理 1 个根中有很多子项的大型 XML 文件

javascript - 将 Flask Session 与新的 EventSource 结合使用

c# - 为什么这个自定义字典类不起作用 - C# 4.0

python - 有什么快速修改这种字典的方法吗?

Python:将 'key:value' 元素的列表解析为 'key' 的字典:值对