例如,假设我想构建一个直方图,我会这样做:
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/