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.
{}
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.
{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.
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