[Tutor] quickie: a better dynamic dictionary update?

Terry Carroll carroll at tjc.com
Wed Jul 12 03:47:11 CEST 2006


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]


lstDeleters = [key for key in myDict.keys() if key not in lstKeepers]
for key in lstDeleters:
    del myDict[key]

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).



More information about the Tutor mailing list