gather information from various files efficiently

Keith Dart kdart at kdart.com
Tue Dec 14 07:13:19 EST 2004


Kent Johnson wrote:
> Keith Dart wrote:
> 
>> try:
>>     dict[a].append(b)
>> except KeyError:
>>     dict[a] = [b]
> 
> 
> or my favorite Python shortcut:
>     dict.setdefault(a, []).append(b)
> 
> Kent

Hey, when did THAT get in there? ;-) That's nice. However, the 
try..except block is a useful pattern for many similiar situations that 
the OP might want to keep in mind. It is usually better than the 
following, also:

if dct.has_key(a):
     dct[a].append(b)
else:
     dct[a] = [b]


Which is a pattern I have seen often.




-- 
                            \/ \/
                            (O O)
-- --------------------oOOo~(_)~oOOo----------------------------------------
Keith Dart <kdart at kdart.com>
vcard: <http://www.kdart.com/~kdart/kdart.vcf>
public key: ID: F3D288E4       URL: <http://www.kdart.com/~kdart/public.key>
============================================================================



More information about the Python-list mailing list