473,378 Members | 1,500 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Storing Instances of Objects in a Nested Dictionary

Hi People,

I am getting frustrated with the way Python handles its dictionary.

I have a scenarion where a class A is stored in a dictionary. The class A contains a dictionary B as a field as below

Expand|Select|Wrap|Line Numbers
  1. class B:
  2.     bName = ""
  3.  
  4. class A:
  5.     aName = ""
  6.     b = {}
  7.  
  8.     def AddB(self, bKey, bVal):
  9.         newB = B()
  10.         newB.bName = bVal
  11.         self.b[bKey] = newB
  12.  
  13. aList = {}
  14.  
  15.  
  16. #Now i attempt to add an instance of A into the dictionary the instance #containing a element in B as below.
  17.  
  18. a1 = A()
  19. a1.name = "first"
  20. a1.AddB("firstValKey", "firstVal")
  21. aList["firstKey"] = a1
  22.  
  23. # I add another instance of A into the the dictionary. Notice hear no element in # B is set
  24. a2 = A()
  25. a2.name = "second"
  26. aList["secondKey"] = a2
  27.  
  28. # Then i print out the contents
  29. for aKey, aValue in aList.iteritems():
  30.     print aKey + "_" + aValue.aName
  31.     for bKey, bValue in aValue.b.iteritems():
  32.       print bKey + "_" + bValue.bName
  33.     print "NEXT"
  34.  
  35.  
# ERROR: I get this result.
secondKey_
_firstValKey_firstVal
NEXT
firstKey_
_firstValKey_firstVal
NEXT

#EXPECTED RESULT
secondKey_
NEXT
firstKey_
_firstValKey_firstVal
NEXT


Question: Can you help me get the desired result. Would be very much appreciated
Nov 28 '07 #1
3 1827
Hi People,

I am getting frustrated with the way Python handles its dictionary.

I have a scenarion where a class A is stored in a dictionary. The class A contains a dictionary B as a field as below

Expand|Select|Wrap|Line Numbers
  1. class B:
  2.     bName = ""
  3.  
  4. class A:
  5.     aName = ""
  6.     b = {}
  7.  
  8.     def AddB(self, bKey, bVal):
  9.         newB = B()
  10.         newB.bName = bVal
  11.         self.b[bKey] = newB
  12.  
  13. aList = {}
  14.  
  15.  
  16. #Now i attempt to add an instance of A into the dictionary the instance #containing a element in B as below.
  17.  
  18. a1 = A()
  19. a1.name = "first"
  20. a1.AddB("firstValKey", "firstVal")
  21. aList["firstKey"] = a1
  22.  
  23. # I add another instance of A into the the dictionary. Notice hear no element in # B is set
  24. a2 = A()
  25. a2.name = "second"
  26. aList["secondKey"] = a2
  27.  
  28. # Then i print out the contents
  29. for aKey, aValue in aList.iteritems():
  30.     print aKey + "_" + aValue.aName
  31.     for bKey, bValue in aValue.b.iteritems():
  32.       print bKey + "_" + bValue.bName
  33.     print "NEXT"
  34.  
  35.  
# ERROR: I get this result.
secondKey_
_firstValKey_firstVal
NEXT
firstKey_
_firstValKey_firstVal
NEXT

#EXPECTED RESULT
secondKey_
NEXT
firstKey_
_firstValKey_firstVal
NEXT


Question: Can you help me get the desired result. Would be very much appreciated
It looks like the dictionary "b" in class "A" is shared with every instance of class "A". I don't know the exact reason for this, but it might have something to do with the items in the dictionary being stored by reference. To fix your problem, modify class "A".
Expand|Select|Wrap|Line Numbers
  1. class A:
  2.  
  3.     aName = ""
  4.  
  5.     def __init__(self):
  6.         self.b = {}
  7.  
  8.     def AddB(self, bKey, bVal):
  9.         newB = B()
  10.         newB.bName = bVal
  11.         self.b[bKey] = newB
Nov 28 '07 #2
It worked like a charm. Many thanks ++
Nov 28 '07 #3
bvdet
2,851 Expert Mod 2GB
Hi People,

I am getting frustrated with the way Python handles its dictionary.

I have a scenarion where a class A is stored in a dictionary. The class A contains a dictionary B as a field as below

Expand|Select|Wrap|Line Numbers
  1. class B:
  2.     bName = ""
  3.  
  4. class A:
  5.     aName = ""
  6.     b = {}
  7.  
  8.     def AddB(self, bKey, bVal):
  9.         newB = B()
  10.         newB.bName = bVal
  11.         self.b[bKey] = newB
  12.  
  13. aList = {}
  14.  
  15.  
  16. #Now i attempt to add an instance of A into the dictionary the instance #containing a element in B as below.
  17.  
  18. a1 = A()
  19. a1.name = "first"
  20. a1.AddB("firstValKey", "firstVal")
  21. aList["firstKey"] = a1
  22.  
  23. # I add another instance of A into the the dictionary. Notice hear no element in # B is set
  24. a2 = A()
  25. a2.name = "second"
  26. aList["secondKey"] = a2
  27.  
  28. # Then i print out the contents
  29. for aKey, aValue in aList.iteritems():
  30.     print aKey + "_" + aValue.aName
  31.     for bKey, bValue in aValue.b.iteritems():
  32.       print bKey + "_" + bValue.bName
  33.     print "NEXT"
  34.  
  35.  
# ERROR: I get this result.
secondKey_
_firstValKey_firstVal
NEXT
firstKey_
_firstValKey_firstVal
NEXT

#EXPECTED RESULT
secondKey_
NEXT
firstKey_
_firstValKey_firstVal
NEXT


Question: Can you help me get the desired result. Would be very much appreciated
Dictionary 'b' is a class variable. Instead of
Expand|Select|Wrap|Line Numbers
  1. self.b[bKey] = newB
it would be proper to do this:
Expand|Select|Wrap|Line Numbers
  1. A.b[bKey] = newB
Class variables are shared among all instances of that class. By creating dictionary 'b' in A.__init__() as KaezarRex suggested, it is an instance variable.
Nov 29 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: Kerry Neilson | last post by:
Hi, Really hung up on this one. I'm trying to get all the fields of a dictionary to be unique for each class: class A { my_dict = dict_entry = { 'key1':0, 'key2':0 } __init__(self): for...
6
by: Bugs | last post by:
Does anyone have any recommendations on the best way to create multiple instances of the same class when the final number of instances is unknown? For example, I have a class and based on some...
3
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 .......
0
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.