How to say $a=$b->{"A"} ||={} in Python?

beginner zyzhu2000 at gmail.com
Fri Aug 17 00:52:18 CEST 2007


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)
>
> --
> Lawrence, oluyede.org - neropercaso.it
> "It is difficult to get a man to understand
> something when his salary depends on not
> understanding it" - Upton Sinclair

I am afraid it is not the same. b.setdefault(k, {}) will always create
an empty dict, even if k is in b, as demonstrated in the below code.

b={}
def f(i):
    print "I am evaluated %d" % i
    return i

b.setdefault('A', f(1))
b.setdefault('A', f(2))
b





More information about the Python-list mailing list