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

在python中,是否可以使用单个命令更新或初始化字典键?,python,dictionary,Python,Dictionary,例如,假设我想建立一个直方图,我会这样做: hist = {} for entry in data: if entry["location"] in hist: hist[entry["location"]] += 1 else: hist[entry["location"]] = 1 有没有办法避免存在性检查并根据密钥的存在情况初始化或更新密钥?这里需要的是一个defaultdict: from collections import defau

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

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

有没有办法避免存在性检查并根据密钥的存在情况初始化或更新密钥?

这里需要的是一个
defaultdict

from collections import defaultdict
hist = defaultdict(int)
for entry in data:
    hist[entry["location"]] += 1
defaultdict
default构造dict中不存在的任何条目,因此对于int,它们从0开始,您只需为每个条目添加一个条目。

是的,您可以执行以下操作:

hist[entry["location"]] = hist.get(entry["location"], 0) + 1
对于引用类型,通常可以使用
setdefault
,但当
dict
的右侧只是一个整数时,这并不合适

Update( hist.setdefault( entry["location"], MakeNewEntry() ) )

三元运算符是一个命令吗

hist[entry["location"]] = hist[entry["location"]]+1 if entry["location"] in hist else 1

(由于我第一次把它弄糟而编辑)

我知道您已经接受了答案,但您也知道,自Python 2.7以来,还有
计数器
模块,它是专门为这种情况设计的

from collections import Counter

hist = Counter()
for entry in data:
    hist[entry['location']] += 1

我甚至不知道它的存在,但它是专门为此而构建的(甚至比defaultdict(int)更重要,尽管两者看起来非常相似)。不错。是的,它很方便,尽管我已经了解到2.7版本依赖性目前限制了它在最终用户应用程序中的部署。