[Tutor] Re: Comparing lines in two files, writing result into a third file

Jeff Shannon jeff@ccvcorp.com
Mon Apr 28 13:19:10 2003

pan@uchicago.edu wrote:

>1) Use the built-in .setdefault() function of a dict for the folloing action:
>    if d.has_key(num): d[num] += 1   # <- increment value, or
>    else: d[num] = 1                 # <- create a new key

Even without using setdefault(), there's a fairly standard
simplification of this relatively common idiom:

d[key] = d.get(key, 0) + 1

The get() dictionary method returns the value associated with key if it
exists, or the second parameter if it doesn't. This effectively gives
you a default value for the dictionary. (I suspect that setdefault()
would simply reroute all dict retrievals to an appropriately-constructed
get() call, or the equivalent thereof...)

Jeff Shannon
Credit International