For instance, say I want to build an histogram, I would go like that:
hist = {}
for entry in data:
if entry["location"] in hist:
hist[entry["location"]] += 1
else:
hist[entry["location"]] = 1
Is there a way to avoid the existence check and initialize or update the key depending on its existence?
What you want here is a
defaultdict:defaultdictdefault-constructs any entry that doesn’t already exist in the dict, so for ints they start out at 0 and you just add one for every item.