How to say $a=$b->{"A"} ||={} in Python?
Nick Craig-Wood
nick at craig-wood.com
Sat Aug 18 06:30:06 EDT 2007
beginner <zyzhu2000 at gmail.com> wrote:
> On Aug 16, 5:43 pm, ra... at dot.com (Lawrence Oluyede) wrote:
> > beginner <zyzhu2... at gmail.com> wrote:
> > > I'd like to do the following in more succint code:
> >
> > > if k in b:
> > > a=b[k]
> > > else:
> > > a={}
> > > b[k]=a
> >
> > b.setdefault(k, a)
> >
>
> I am afraid it is not the same. b.setdefault(k, {}) will always create
> an empty dict, even if k is in b
That is certainly true, but does it matter? You waste a very small
amount of time creating a dict you don't use.
$ python -m timeit '{}'
1000000 loops, best of 3: 0.247 usec per loop
On my machine 250 ns gets you a new dict...
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list