Newbie lists question
Gerhard Häring
gerhard.nospam at bigfoot.de
Mon Aug 13 19:07:34 EDT 2001
(Let's hope the supersede feature works, else please ignore the previous
posting)
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?
I am not aware of a nicer solution with dictionaries, short of writing yet
another MultiDict class.
>#!/usr/bin/python
>
>import os, time, glob, string
>
>backupdir = glob.glob("/netbackups/.disks/disk*/*.out")
>
>prefixes = {}
>
>for file in backupdir:
> filename = string.split(file, '/')[-1]
> prefix = string.split(filename,'.')[0]
> if prefixes.has_key(prefix): # This is the loop
>I think is tres' ugly
> 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)
>[...]
If you insist on improving something, you could use the functions in os.path,
(like os.path.split and os.path.splitext) instead of doing the splitting
yourself ;-)
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