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

Paul McGuire ptmcg at austin.rr.com
Thu Aug 16 22:09:39 EDT 2007


On Aug 16, 6:03 pm, Carl Banks <pavlovevide... at gmail.com> wrote:
> On Aug 16, 6:35 pm, beginner <zyzhu2... at gmail.com> wrote:
>
> > Hi All.
>
> > I'd like to do the following in more succint code:
>
> > if k in b:
> >     a=b[k]
> > else:
> >     a={}
> >     b[k]=a
>
> > a['A']=1
>
> > In perl it is just one line: $a=$b->{"A"} ||={}.
>
> > Thanks,
> > Geoffrey
>
> Define b as a default dict:
>
> b = defaultdict(dict)
> b[k]['A'] = l
>
> Carl Banks- Hide quoted text -
>
> - Show quoted text -

I think the most direct translation of the OP's example to Python
would be:

# setup b as special flavor of dict, that creates a
# new dict for not-yet-created keys
b = defaultdict(dict)

# actual python impl of $a=$b->{k}||={}
a = b[k]

# assign 1 to retrieved/created dict
a['A'] = 1

-- Paul




More information about the Python-list mailing list