how can I clear a dictionary in python

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Mar 29 10:38:34 EDT 2007


Larry Bates a écrit :
> Aahz wrote:
>> In article <4_SdndYI-pFUbZfbnZ2dnUVZ_hzinZ2d at comcast.com>,
>> Larry Bates  <lbates at websafe.com> wrote:
>>> Marko.Cain.23 at gmail.com wrote:
>>>> I create a dictionary like this
>>>> myDict = {}
>>>>
>>>> and I add entry like this:
>>>> myDict['a'] = 1
>>>> but how can I empty the whole dictionary?
>>> just point myDict to an empty dictionary again
>>>
>>> myDict={}
>> Go back and read Christian's post, then post a followup explaning why his
>> solution is better than yours.  Your explanation should use id().
> 
> I believe he (as many new to Python do) are mired in old
> programming thinking that variables "contain" things.

Does "he" refer to Christian Tismer ? If so, you may want to use google 
and correct your beliefs (hint: does 'stackless Python' ring a bell ?).

> As I'm sure you kno, variables point to things in Python.

(conceptually) names are keys associated with an object in a given 
namespace. FWIW, be assured that Christians knows this pretty well.

> I don't believe that there are lots of other objects
> pointing to this dictionary.

You just cannot *know* this. This might be true now, this might be false 
now, and this might change anytime. Assuming anything here is the road 
to disaster. Don't assume, do the righ thing.

>  Perhaps the OP can clarify
> for us.  If there aren't other objects pointing to
> this dictionary it would make NO sense to iterate over a
> dictionary and delete all the keys/values

You don't iterate over anything. Dicts being the central datastructure 
in Python, you can bet your ass they are optimized to death (or near 
death). If you have any doubt, then still don't assume : verify (hint: 
import timeit). And yet even if clearing a dict happens to be a bit 
slower than instanciating a new one, rebinding a name and mutating an 
object are still two very different concepts in Python, with very 
different consequences. The OP explicitely asked for clearing a dict, 
not for creating a new one.

> so I tried to read
> between the lines

Why ?

> and answer what I believe the OP thought he
> was asking.

What the OP asked was quite clear, and not subject to any 
interpretation. And the correct answer is obviously not the one you gave.

>  BTW-I didn't see you posting an answer to what
> you thought was the "correct" question, just criticizing me
> for taking the time to answer what I perceived the OP was
> asking.

If you cannot understand the difference between criticism and a friendly 
correction,  nor why you should actually thank the one correcting you 
when you're wrong, I guess there's no point trying explaining why 
correcting wrong answers on newsgroups is actually important.



More information about the Python-list mailing list