How to say $a=$b->{"A"} ||={} in Python?
beginner
zyzhu2000 at gmail.com
Fri Aug 17 09:41:57 EDT 2007
On Aug 17, 2:35 am, Sébastien Buchoux <seb.buch... at gmail.com> wrote:
> beginner a écrit :
>
>
>
> > 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
>
> One solution I often use in such cases:
>
> try:
> a = b[k]
> except KeyError: #or except IndexError: if b is a list/tuple and not a dict
> a = {}
> b[k] = a
>
> a['A'] = 1
>
> Indeed, exceptions are handled faster than "if/else" loops. As it was
> mentionned earlier, One neat solution in Perl may not be the perfect one
> in Python.
>
> Cheers,
>
> Sébastien- Hide quoted text -
>
> - Show quoted text -
Wow. This solution is interesting. I'll try this. Thanks.
More information about the Python-list
mailing list