Perlish dictionary behavior
Robert Brewer
fumanchu at amor.org
Thu Jun 3 16:27:25 EDT 2004
Chris wrote:
> 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}++;
> }
>8
> 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.
Here's one way:
>>> class AllThingsStartAtZero(dict):
... def __getitem__(self, key):
... return dict.get(self, key, 0)
...
>>> thingCounts = AllThingsStartAtZero()
>>> for thing in ('a', 'b', 'c', 'd', 'a'):
... thingCounts[thing] += 1
...
>>> thingCounts
{'a': 2, 'c': 1, 'b': 1, 'd': 1}
Notice that a actually does get 'incremented twice'.
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list