Newbie lists question

Gerhard Häring gerhard.nospam at bigfoot.de
Mon Aug 13 19:34:10 EDT 2001


On Tue, 14 Aug 2001 01:07:34 +0200, Gerhard Häring wrote:
>On Mon, 13 Aug 2001 15:17:57 -0700, Wolfe Maykut <wolfe at spam.me.not> wrote:
>>    Hi.  I'm trying to create a list on the end of a dictionary.   I'd
>>like to have a single loop, but since the dictionary is dynamically
>>generated it appears as if I have to test to see if the key is around
>>and then treat each case differently in order to initialize the loop.
>>It looks ugly.  Is there a nicer way of doing this that I'm missing?

>>[...]
>>    # This is the loop I think is tres' ugly:
>>    if prefixes.has_key(prefix):   
>>       prefixes[prefix].append(file)
>>    else:
>>        prefixes[prefix] = []
>>        prefixes[prefix].append(file)
>
>I don't think this is ugly, it does even get quite nice when rewriting it:
>
>if not prefixes.has_key(prefix):
>    prefixes[prefix] = []
>prefixes[prefix].append(file)

Well, I found out it is possible to write this shorter with the setdefault()
method of the dictionary, but I find it also less readable:

prefixes[prefix] = prefixes.setdefault(prefix, []) + [file]

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    public key at homepage
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))



More information about the Python-list mailing list