The get
method of a dict (like for example characters
works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError
it returns the default value (if you call .get
with just one argument, the key, the default value is None
).
So an equivalent Python function (where calling myget(d, k, v)
is just like d.get(k, v)
might be:
def myget(d, k, v=None):
try: return d[k]
except KeyError: return v
The sample code in your Q is clearly trying to count the number of occurrences of each character: if it already has a count for a given character, get
returns it (so it's just incremented by one), else get
returns 0 (so the incrementing correctly gives 1
at a character's first occurrence in the string).