[Tutor] quickie: a better dynamic dictionary update?
Terry Carroll
carroll at tjc.com
Wed Jul 12 03:57:26 CEST 2006
On Tue, 11 Jul 2006, Terry Carroll wrote:
> On Tue, 11 Jul 2006, Marcus Goldfish wrote:
>
> > # 1st, find the 'stale' items in our dictionary to delete
> > # lstKeepers is a list of current pictures
> > # Note: if I try to iterate over the keys of the dict and
> > # remove-as-I-go, I get an exception (dict size changed
> > # during iteration)
> > lstRemove = []
> > for key in myDict:
> > if key not in lstKeepers:
> > lstRemove.append(key)
> >
> > # 2nd, remove them
> > for oldKey in lstRemove:
> > del myDict[oldKey]
>
> [snip code]
> It's still a two-passer, but I don't see straightforward any way around
> that, if you want to update the dictionary (as opposed to making a new
> dictionary with the result, which could probably be done with an
> excessively clever list comprehension).
Actually, it turns out not to be excessively clever at all (if I could do
it):
myDict = dict([(key, myDict[key]) for key in myDict.keys()
if key in lstKeepers])
I'm not sure it's any nicer looking, though, than my first suggestion
(although my first suggestion is probably a little slower).
More information about the Tutor
mailing list