problem with nested dictionaries

Jef Mangelschots jef.mangelschots at iname.com
Thu Oct 3 05:35:37 CEST 2002


Hi,

 in the below example, I want to create a dictionary of C2-objects.
Each C2-object has a member-dictionary of C1-objects.

In the sample code, I only insert values in the dictionary from object
'3'. 

However, when I print out the list, the objects which I inserted under
C2-object '3', appear to have been inserted in the other objects as
well.

What am I doing wrong (just started with python)

I am using Python 2.2


#<< begin snip

class C1:
    class_C1_name = ""
    def __init__(self, n):
        self.class_C1_name = n

class C2:
    class_C2_name = ""
    a_list     = {}
    def __init__(self, n):
        self.class_C2_name = n


C2_LIST = {}


C2_LIST['1'] = C2("C2_1")
C2_LIST['2'] = C2("C2_2")
C2_LIST['3'] = C2("C2_3")
C2_LIST['4'] = C2("C2_4")

C2_LIST['3'].a_list['5'] = C1("C1_5")
C2_LIST['3'].a_list['6'] = C1("C1_6")
C2_LIST['3'].a_list['7'] = C1("C1_7")


for c2_name in C2_LIST:
    print "name: " + c2_name
    for c1_name in C2_LIST[c2_name].a_list:
        print "  name: " + c1_name

# >> end snip

output:

name: 1
  name: 5
  name: 7
  name: 6
name: 3
  name: 5
  name: 7
  name: 6
name: 2
  name: 5
  name: 7
  name: 6
name: 4
  name: 5
  name: 7
  name: 6




More information about the Python-list mailing list