Friday, December 25, 2015

Small python trick: Better way to init dictionary

From my php and perl background I remember that named arrays or hashes should be initialize correctly, like this:
if (haskey(x, somehash)) {
  somehash[x] += y;
} else {
  somehash[x] = y;
}

And it looks like a tumour inside a python code. But .get() method can cure it:
somedict[x] = somedict.get(x, 0) + y

Looks much better! 

No comments:

Post a Comment