Perlish dictionary behavior

Larry Bates lbates at swamisoft.com
Thu Jun 3 23:08:36 CEST 2004


You can do this with:

thingCounts={}
for thing in file:
    thingCounts[thing]=thingCounts.get(thing, 0)+1

Larry Bates
Syscon, Inc.

"Chris" <bit_bucket5 at hotmail.com> wrote in message
news:fa7108b0.0406031202.6ab7cc8d at posting.google.com...
> 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