2005-04-27-0341Z


Just found a better (?) way to do something in Python for which I often have a need: a counting dictionary, one that doesn't croak when you try to increment a nonexistent key:

$ python
Python 2.4 (#1, Dec  4 2004, 20:10:33)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class countdict(dict):
...  def __getitem__(self, key):
...   try:
...    return dict.__getitem__(key)
...   except:
...    return 0
...
>>> a = countdict()
>>> a
{}
>>> a['t']
0
>>> a['b'] += 1
>>> a
{'b': 1}
>>>

Not sure I got the bugs out yet, but it looks promising. I love elegance in a programming language.

Back to blog or home page

last updated 2013-01-10 20:36:42. served from tektonic.jcomeau.com