[Tutor] Behaviour of dictionaries and others when deleting?
Kent Johnson
kent37 at tds.net
Tue May 22 03:17:19 CEST 2007
Bill Campbell wrote:
> Is the behaviour defined if one is processing a dictionary using
> iteritems, and delete items?
>
> for k, v in d.iteritems():
> if somecondition(k, v): del d[k]
>
> Would this process all the original members of the dictionary?
This is not well-defined. You can use
for k, v in d.items():
which creates a new list to hold the items and iterates that.
> I've always been leary of deleting items while processing things
> like this, keeping a list of keys to be deleted, then processing
> that list upon completion of the mail loop to delete the items
> from the original dictionary or database file.
I don't know about bsddb but for lists and dicts that is the right
approach. You can also use a list comprehension to filter a list or dict.
Kent
More information about the Tutor
mailing list