defaultdict's bug or feature?

MRAB google at mrabarnett.plus.com
Thu May 21 20:55:00 EDT 2009


Red Forks wrote:
> You mean 'get' method should not alter the dict, does 'dict[key]' should 
> not alter the dict either?
> 
> d = defaultdict(set)
> assert len(d) == 0
> print d[1]
> assert len(d) == 1
> 
> auto insert value to dict, when value is not in dict, is what 
> defaultdict try to do.
> 
That's the behaviour which makes defaultdict so useful. Compare using
defaultdict:

     d = defaultdict(int)

and then:

     d["foo"] += 1

to using dict:

     d = {}

and then:

     try:
         d["foo"] += 1
     except KeyError:
         d["foo"] = 1

or:

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



More information about the Python-list mailing list