例如,假设我想建立一个直方图,我会这样:
hist = {}
for entry in data:
if entry["location"] in hist:
hist[entry["location"]] += 1
else:
hist[entry["location"]] = 1
Run Code Online (Sandbox Code Playgroud)
有没有办法避免存在检查,并根据其存在初始化或更新密钥?
Pet*_*ter 19
你想要的是defaultdict:
from collections import defaultdict
hist = defaultdict(int)
for entry in data:
hist[entry["location"]] += 1
Run Code Online (Sandbox Code Playgroud)
defaultdict default-构造dict中尚不存在的任何条目,因此对于int,它们从0开始,你只需为每个项添加一个.
CB *_*ley 11
是的,你可以这样做:
hist[entry["location"]] = hist.get(entry["location"], 0) + 1
Run Code Online (Sandbox Code Playgroud)
对于引用类型,您通常可以setdefault用于此目的,但是当您的右侧dict只是一个整数时,这是不合适的.
Update( hist.setdefault( entry["location"], MakeNewEntry() ) )
Run Code Online (Sandbox Code Playgroud)
小智 6
我知道你已经接受了答案但是你知道,自从Python 2.7以来,还有一个Counter模块,它明确地针对这种情况.
from collections import Counter
hist = Counter()
for entry in data:
hist[entry['location']] += 1
Run Code Online (Sandbox Code Playgroud)
http://docs.python.org/library/collections.html#collections.Counter