473,698 Members | 2,185 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When to clear a dictionary...

What is the benefit of clearing a dictionary, when you can just reassign
it as empty? Similarly, suppose I generate a new dictionary b, and need
to have it accessible from a. What is the best method, under which
circumstances?
>>import some_function
>>a = {1:2,3:4}
b = {1:2:4:3}
a.clear()
a.update(b)
>>a = {1:2,3:4}
b = {1:2,4:3}
for key in b:
.... a[key] = b[key]
>>a = {1:2,3:4}
b = {1:2,4:3}
a = b
Apr 20 '07 #1
5 1945
Bill Jackson wrote the following on 04/20/2007 09:48 AM:
>>import some_function
>>a = {1:2,3:4}
>>b = {1:2:4:3}
>>a.clear()
>>a.update(b)
>>a = {1:2,3:4}
>>b = {1:2,4:3}
>>for key in b:
.... a[key] = b[key]
Clearly, this won't have the same result as the other two examples.
>
>>a = {1:2,3:4}
>>b = {1:2,4:3}
>>a = b
Apr 20 '07 #2
Bill Jackson wrote:
What is the benefit of clearing a dictionary, when you can just reassign
it as empty?
If you have objects that point to the dictionary (something like a cache)
then you want to clear the existing dictionary instead of just assigning
it to empty. If nothing points to it, assigning it to empty is fast and
you can let garbage collection do the rest.
Similarly, suppose I generate a new dictionary b, and need
to have it accessible from a. What is the best method, under which
circumstances?
>>>import some_function
>>>a = {1:2,3:4}
b = {1:2:4:3}
a.clear()
a.update(b )
>>>a = {1:2,3:4}
b = {1:2,4:3}
for key in b:
... a[key] = b[key]
>>>a = {1:2,3:4}
b = {1:2,4:3}
a = b
Syntax error in the first example but if you fix that the first two are
equivalent (but I would suspect that the second would be faster for large
dictionaries).

The third example both a and b point to the same dictionary after the a=b
which you can see from:
>>a is b
True
>>id(a)
31760224
>>id(b)
31760224
>>>
-Larry

Apr 20 '07 #3
En Fri, 20 Apr 2007 14:28:00 -0300, Larry Bates <la*********@we bsafe.com>
escribió:
Bill Jackson wrote:
>What is the benefit of clearing a dictionary, when you can just reassign
it as empty?

If you have objects that point to the dictionary (something like a cache)
then you want to clear the existing dictionary instead of just assigning
it to empty. If nothing points to it, assigning it to empty is fast and
you can let garbage collection do the rest.
For an actual comparision, see Alex Martelli posts a few days ago:
http://mail.python.org/pipermail/pyt...ch/433027.html
>>>>a = {1:2,3:4}
b = {1:2:4:3}
a.clear()
a.update( b)
>>>>a = {1:2,3:4}
b = {1:2,4:3}
for key in b:
... a[key] = b[key]
Syntax error in the first example but if you fix that the first two are
equivalent (but I would suspect that the second would be faster for large
dictionaries).
It's the other way; the first method contains a single Python function
call and most of the work is done in C code; the second does the iteration
in Python code and is about 4x slower.
python -m timeit -s "b=dict.fromkey s(range(10000)) ;a={}" "a.update(b )"
100 loops, best of 3: 10.2 msec per loop
python -m timeit -s "b=dict.fromkey s(range(10000)) ;a={}" "for key in b:
a[key]=b[key]"
10 loops, best of 3: 39.6 msec per loop

--
Gabriel Genellina
Apr 20 '07 #4
Gabriel Genellina wrote:
En Fri, 20 Apr 2007 14:28:00 -0300, Larry Bates
<la*********@we bsafe.comescrib ió:
>Bill Jackson wrote:
>>What is the benefit of clearing a dictionary, when you can just reassign
it as empty?

If you have objects that point to the dictionary (something like a cache)
then you want to clear the existing dictionary instead of just assigning
it to empty. If nothing points to it, assigning it to empty is fast and
you can let garbage collection do the rest.

For an actual comparision, see Alex Martelli posts a few days ago:
http://mail.python.org/pipermail/pyt...ch/433027.html
>>>>>a = {1:2,3:4}
>b = {1:2:4:3}
>a.clear( )
>a.update(b )

>a = {1:2,3:4}
>b = {1:2,4:3}
>for key in b:
... a[key] = b[key]
>Syntax error in the first example but if you fix that the first two are
equivalent (but I would suspect that the second would be faster for large
dictionaries ).

It's the other way; the first method contains a single Python function
call and most of the work is done in C code; the second does the
iteration in Python code and is about 4x slower.
>python -m timeit -s "b=dict.fromkey s(range(10000)) ;a={}" "a.update(b )"
100 loops, best of 3: 10.2 msec per loop
>python -m timeit -s "b=dict.fromkey s(range(10000)) ;a={}" "for key in
b: a[key]=b[key]"
10 loops, best of 3: 39.6 msec per loop

--Gabriel Genellina
That is what I meant to say, thanks for catching the error.

-Larry
Apr 20 '07 #5
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(bd ict)
(3) "I want the data in bdict to be copied into adict, throwing away
whatever was already there."

Solution:

adict.clear()
adict.update(bd ict)
(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(k ey):
pass # ignore it
else:
adict[key] = bdict[key] # add it
--
Steven.

Apr 21 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
4055
by: Alan Silver | last post by:
Hello, I have a server running Windows Server 2003, on which two of the web sites use the MegaBBS ASP forum software. Both sites suddenly developed the same error, which seems to be connected to the dictionary object. After some tinkering, I whittled it down to the following (complete) ASP... <%@ CodePage=65001 Language="VBScript"%>
1
9250
by: john wright | last post by:
I have a dictionary oject I created and I want to bind a listbox to it. I am including the code for the dictionary object. Here is the error I am getting: "System.Exception: Complex DataBinding accepts as a data source either an IList or an IListSource at System.Windows.Forms.ListControl.set_DataSource(Object value)
5
1469
by: Russell Warren | last post by:
I just ran across a case which seems like an odd exception to either what I understand as the "normal" variable lookup scheme in an instance/object heirarchy, or to the rules regarding variable usage before creation. Check this out: >>> class foo(object): .... I = 1 .... def __init__(self): .... print self.__dict__ .... self.I += 1
1
4506
by: Martin Widmer | last post by:
Hi Folks. When I iterate through my custom designed collection, I always get the error: "Unable to cast object of type 'System.Collections.DictionaryEntry' to type 'ContentObjects.ContentBlock'." The error occurs at the "For...Each" line if this method:
0
1424
by: BLinfield | last post by:
I'm new to .Net and I inherited a Web App from some guys who left the company. The App stores some stuff from the Database in a Dictionary so that the first time the data is accessed it is slow but the next time it is fast. The App locks the Dictionary whenever it puts something from the database into the dictionary - and then it returns it to the caller. But when the data is already in the dictionary it just returns the data without locking...
0
1320
by: xpding | last post by:
Hello, I have a class MyEmbededList contains a generic dictionary, the value field is actually the MyEmbededList type as well. There is another class need to access and manipulate a list of MyEmbededList (please refer to the MyTestClass below). I am not sure whether I implements the right locking mechanism here and hope someone can give me some advices. I have provided some codes for these two classes below. My questions are: 1. Am I...
18
2962
by: Marko.Cain.23 | last post by:
Hi, I create a dictionary like this myDict = {} and I add entry like this: myDict = 1 but how can I empty the whole dictionary? Thank you.
39
2462
by: Alan Isaac | last post by:
This may seem very strange, but it is true. If I delete a .pyc file, my program executes with a different state! In a single directory I have module1 and module2. module1 imports random and MyClass from module2. module2 does not import random. module1 sets a seed like this::
1
2209
by: joeedh | last post by:
Hi I'm getting extremely odd behavior. First of all, why isn't PyEval_EvalCode documented anywhere? Anyway, I'm working on blender's python integration (it embeds python, as opposed to python embedding it). I have a function that executes a string buffer of python code, fetches a function from its global dictionary then calls it. When the function code returns a local variable, PyObject_Call() appears to be returning garbage. ...
0
8668
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8598
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9152
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9014
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7708
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6515
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4358
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4612
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.