[Tutor] Behaviour of dictionaries and others when deleting?
Bill Campbell
bill at celestial.net
Tue May 22 23:38:46 CEST 2007
On Mon, May 21, 2007, Kent Johnson wrote:
>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.
Thanks for the feeback Kent. It confirms my thoughts.
Using the 2nd method, d.items(), can be an issue with very large
dictionaries (although I tend use the Berkeley databases for
these when dealing with very large data sets).
>> 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.
The places where I'm really concerned with this is dealing with
large databases, say a few million records with info on all data
storage on a server.
Bill
--
INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software, LLC
URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way
FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676
If you think health care is expensive now, wait until you see what it coses
when it's free -- P.J. O'Rourke
More information about the Tutor
mailing list