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

Sébastien Buchoux seb.buchoux at gmail.com
Fri Aug 17 03:35:47 EDT 2007


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



More information about the Python-list mailing list