Perlish dictionary behavior

Chris bit_bucket5 at hotmail.com
Thu Jun 3 16:02:03 EDT 2004


One nice thing about Perl that is helpful when tallying things up by
type is that if you increment a hash key and the key does not exist,
Perl puts a one there.  So you can have code that does something like
this:

my %thingCounts;
foreach my $thing(<file>)
{
  $thingCounts{$thing}++;
}

(I think the syntax is right, but with Perl I never am sure).

In Python, this would generate a KeyError.  So you'd do something like

thingCounts = {}
for thing in file:
  try:
    thingCounts[thing] += 1
  except KeyError:
    thingCounts[thing] = 1

Is there any clever way to be able to just say, like in Perl, 
for thing in file:
  thingCounts[thing] += 1

and have it do the above?  Perhaps with a custom dictionary class or
something?  Just wondering what that might look like.

Just curious.  Thanks.
-Chris



More information about the Python-list mailing list