When to clear a dictionary...

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Fri Apr 20 21:48:33 EDT 2007


On Fri, 20 Apr 2007 09:48:07 -0700, Bill Jackson wrote:

> What is the benefit of clearing a dictionary, when you can just reassign 
> it as empty?

They are two different things. In the first place, you clear the
dictionary. In the second place, you reassign the name to a new object
(which may be an empty dictionary, or anything else) while leaving the
dictionary as-is.

Here's an example of clearing the dictionary.

>>> adict = {1:"parrot"}
>>> bdict = adict
>>> adict.clear()
>>> bdict
{}

Because both adict and bdict point to the same dictionary object,
clearing it results in an empty dictionary no matter what name (if any!)
you use to refer to it.

Here's an example of re-assigning the name.

>>> adict = {1:"parrot"}
>>> bdict = adict
>>> adict = {} # re-assign the name to an empty dict
>>> bdict
{1: 'parrot'}

Although adict and bdict both start off pointing to the same dictionary,
once you re-assign the name adict, they now point to different
dictionaries, only one of which is empty.

In this specific case, if bdict didn't exist, the original dictionary
would then be garbage-collected and the memory re-claimed. In the C
implementation of Python (CPython), that will happen immediately; in
the Java and (I think) .Net implementations of Python (Jython and
IronPython) it will happen "eventually", with no guarantee of how long it
will take.

> Similarly, suppose I generate a new dictionary b, and need 
> to have it accessible from a.  What is the best method, under which 
> circumstances?

That depends on what you are trying to do.

>>> adict = {1: "parrot"}
>>> bdict = {2: "spam")

What is it that you want to do?

(1) "I want the name 'adict' to point to the same dict as bdict."

Solution:

adict = bdict


(2) "I want the data in bdict to update the data in adict, keeping items
in adict that are not in bdict but replacing them if they are in bdict."

Solution:

adict.update(bdict)


(3) "I want the data in bdict to be copied into adict, throwing away
whatever was already there."

Solution:

adict.clear()
adict.update(bdict)


(4) "I want the data in bdict to be copied into adict, but keeping what
was already there."

Solution:

for key in bdict:
    if adict.has_key(key):
        pass # ignore it
    else:
        adict[key] = bdict[key] # add it


-- 
Steven.




More information about the Python-list mailing list