[Tutor] quickie: a better dynamic dictionary update?

John Fouhy john at fouhy.net
Wed Jul 12 04:03:51 CEST 2006


On 12/07/06, Marcus Goldfish <magoldfish at gmail.com> 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)

Try this:

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

The difference here is that myDict.keys() creates a list containing
the keys of myDict at the start of the loop, and then iterates over
the list.

If lstKeepers is big, it might be more efficient to make it into a set first ---

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

-- 
John.


More information about the Tutor mailing list