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
:
from collections import defaultdict
hist = defaultdict(int)
for entry in data:
hist[entry["location"]] += 1
defaultdict
default-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.
Yes, you can do:
hist[entry["location"]] = hist.get(entry["location"], 0) + 1
With reference types, you can often use setdefault
for this purpose, but this isn't appropriate when the right hand side of your dict
is just an integer.
Update( hist.setdefault( entry["location"], MakeNewEntry() ) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With