473,813 Members | 2,802 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Working with copies of a dictionary

Hi!

Damnit, am I angry! Please look at the following example:

class bla:
def __init__(self):
self.ho = {'a': ['b'], 'c': ['b', 'e', 'f', 'd'], 'b':
['a', 'e', 'f', 'c'], 'e': ['b', 'c', 'g', 'h'], 'd': ['c'], 'g': ['e',
'h'], 'f': ['b', 'c'], 'h': ['e', 'g']} # shall be an adjacence list of
a graph...
self.oha = [('a', 'b'), ('b', 'c'), ('b', 'e'), ('b', 'f'),
('c', 'd'), ('c', 'e'), ('c', 'f'), ('e', 'g'), ('e', 'h'), ('g', 'h')]
def do_stuff(self):
next = self.ho.copy() # HERE!!!

edges = self.oha[:]

next['c'].remove('e')
next['g'].remove('h')
del next['b']
edges.pop(0)
edges.pop(3)
edges.pop(6)

f = bla()
print f.ho
print f.oha

OK, so the two last lines, what surprising thing give me exactly the
long dictionary I defined in __init__.

f.do_stuff()

Now you see that I do nothing with the self.* thingies themselves. So
why in hell do the following two lines give me a different output???

print f.ho
print f.oha

f.oha hasn't changed, but f.ho now lacks the two elements I deleted
from next with the remove() call, while the 'b' array is still there.
Now can anyone please explain me why do_stuff() ha changed the
attributes of the class?? Even the following:

next = {}
for v, e in self.ho.items() :
next[v] = e

, where one can easily see that next does not even have the slightest
connection to f.ho, changes it!! I am completely desparate, because I
would just like to work with the copy of that dictionary, without
deleting the proper one. How can I do such a thing?

Thanks in Advance
Tobias

--
please send any mail to botedesschatten s(at)web(dot)de
Jul 18 '05 #1
2 1666

"Tobias Pfeiffer" <me@privacy.net > wrote in message
news:br******** ****@ID-162581.news.uni-berlin.de...
Hi!

Damnit, am I angry! Please look at the following example:

class bla:
def __init__(self):
self.ho = {'a': ['b'], 'c': ['b', 'e', 'f', 'd'], 'b':
['a', 'e', 'f', 'c'], 'e': ['b', 'c', 'g', 'h'], 'd': ['c'], 'g': ['e',
'h'], 'f': ['b', 'c'], 'h': ['e', 'g']} # shall be an adjacence list of
a graph...
self.oha = [('a', 'b'), ('b', 'c'), ('b', 'e'), ('b', 'f'),
('c', 'd'), ('c', 'e'), ('c', 'f'), ('e', 'g'), ('e', 'h'), ('g', 'h')]
def do_stuff(self):
next = self.ho.copy() # HERE!!!

edges = self.oha[:]

next['c'].remove('e')
next['g'].remove('h')
del next['b']
edges.pop(0)
edges.pop(3)
edges.pop(6)

f = bla()
print f.ho
print f.oha

OK, so the two last lines, what surprising thing give me exactly the
long dictionary I defined in __init__.

f.do_stuff()

Now you see that I do nothing with the self.* thingies themselves. So
why in hell do the following two lines give me a different output???

print f.ho
print f.oha

f.oha hasn't changed, but f.ho now lacks the two elements I deleted
from next with the remove() call, while the 'b' array is still there.
Now can anyone please explain me why do_stuff() ha changed the
attributes of the class?? Even the following:

next = {}
for v, e in self.ho.items() :
next[v] = e

, where one can easily see that next does not even have the slightest
connection to f.ho, changes it!! I am completely desparate, because I
would just like to work with the copy of that dictionary, without
deleting the proper one. How can I do such a thing?

Thanks in Advance
Tobias

--
please send any mail to botedesschatten s(at)web(dot)de


Not even the slightest connection is not quite right.
adict = {'a':[1,2,3], 'b':[3,4,5]}
anotherdict = adict.copy()
id(adict['a']) 10410608 id(anotherdict['a']) 10410608
adict['a'] and anotherdict['a'] reference the same list. Try a deep copy.
import copy
a_third_dict = copy.deepcopy(a dict)
a_third_dict {'a': [1, 2, 3], 'b': [3, 4, 5]} id(adict3['a'])

10411984

Duncan
Jul 18 '05 #2
[snip]

Not even the slightest connection is not quite right.
adict = {'a':[1,2,3], 'b':[3,4,5]}
anotherdict = adict.copy()
id(adict['a']) 10410608 id(anotherdict['a']) 10410608
adict['a'] and anotherdict['a'] reference the same list. Try a deep copy.
import copy
a_third_dict = copy.deepcopy(a dict)
a_third_dict {'a': [1, 2, 3], 'b': [3, 4, 5]} id(adict3['a']) 10411984

Duncan


Of course I shouldn't edit output once I've pasted it. That should be,
id(a_third_dict['a'])

10411984
Jul 18 '05 #3

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

Similar topics

4
4505
by: earwicker | last post by:
I recently deployed a web application which contains a user registration form with the usual fields: name, address, email, password, etc. Each of the TextBoxes uses a validation control to verify the input. On my development server, this form works precisely as expected. When I deploy the app to the production server (a hosting service), the client-side validation quits working altogether. Now, I KNOW that scripts are enabled and working...
10
3533
by: erin.sebastian | last post by:
Hello Everyone, I have code that uploads files in asp. It seems to be working however on files > 200kb it bombs and i don't know why. Does anyone have any idea of why this would occur and what i can do to fix it? Thank you in advance!!!!
0
2348
by: serkan | last post by:
Guys, I am trying to get this password reset functionality wor for me but I am not successful at all. Please somebody help me. I get "Your password could not be reset - please try again later" so I think the get_random_word function is not working right. Here are the scripts: This is the script after the user enters his/her userid. <?php require_once("bookmark_fns.php"); // creating short variable name $username = $_POST;
5
2871
by: Joel Barsotti | last post by:
I'm trying to get sql cache dependency working correctly. I've got sql server 2005 for my back end. I've don the "ALTER DATABASE dbName SET broker_enable" command. I made sure the user in my connection string has subscripe notifications permission set to grant. But now it seems that the cache is kicking my product out of the cache
5
1800
by: fakeprogress | last post by:
For a homework assignment in my Data Structures/C++ class, I have to create the interface and implementation for a class called Book, create objects within the class, and process transactions that manipulate (and report on) members of the class. Interface consists of: - 5 private variables char author; char title; char code;
3
1768
by: Girish Sahani | last post by:
hi ppl, Here is a simple function to remove those keys of a dictionary whose values are less than some specified value. But it isnt working. Please help. def prune(d,cp): l = for rule,value in d.iteritems(): #print value if value >= cp:
5
2755
by: Defected | last post by:
Hi All, I have problem whit this program, because the output file print copies but only at the end of file, and the file does not have two copies of the same element. Example of elements in the two file: 11 Sodium Na 22.99 20 Calcium Ca 40.08
3
1498
by: mk | last post by:
Hello everyone, I'm storing functions in a dictionary (this is basically for cooking up my own fancy schmancy callback scheme, mainly for learning purpose): .... return "f2 " + arg .... .... return "f1" + arg ....
0
187
by: Calvin Spealman | last post by:
On Thu, Jul 17, 2008 at 7:45 AM, mk <mrkafk@gmail.comwrote: As was pointed out already, this is a basic misunderstanding of assignment, which is common with people learning Python. To your actual problem... Why do you wanna do this anyway? If you want to change the function in the dictionary, why don't you simply define the functions you'll want to use, and change the one you have bound to the key in the dictionary when you want to...
0
9734
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
9607
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
10669
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
10407
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...
1
10424
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7684
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
6897
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4358
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
2
3885
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.