At 07:59 PM 7/9/2007 +0100, tav wrote: >>PEP 3100 suggests dict.setdefault() may be removed in Python 3, since >>it is in principle no longer necessary (due to the new defaultdict type). >> >>However, there is another class of use cases which use setdefault for >>its limited atomic properties - the initialization of non-mutated >>data structures that are shared among threads. (And defaultdict >>cannot achieve the same thing.) > >+1 > >setdefault's ability to return current value is also a very useful >functionality and has saved writing: > > if key not in dict: > value = <compute-value> > dict[key] = value > >with the simpler: > > value = dict.setdefault(key, <compute-value>) > >Is there a better way to do the above without .setdefault?
Yes, in 2.5 there's collections.defaultdict. Of course, that only works if there is a fixed mapping from keys to initial computed values for the entire dictionary for all time. Oh, and if your code gets to create the dictionary. :) _______________________________________________ Python-3000 mailing list Python-3000@python.org http://mail.python.org/mailman/listinfo/python-3000 Unsubscribe: http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com