user711762
user711762

Reputation: 3

Python Dictionary List

originally I had my program like so:

inst = {}
class IContainer:
    dicList = {}


for i in range(10):
        inst[i] = IContainer()

def FindEnd(node):
    if node.text != None:
        inst[counter].dicList[node.tag] = node.text
    else:
        for subNode in node:
            FindEnd(subNode)

counter = 0
for element in root:
    if element.tag == "Items":
        for subE in element:
            if subE.tag == "Item":
                for subSubE in subE:
                    FindEnd(subSubE, counter)
                counter += 1

that works just fine i was able to parse stuff into a dictionary, I want to create the list dynamically instead.

so

counter = 0
for element in root:
    if element.tag == "Items":
        for subE in element:
            if subE.tag == "Item":
                inst[counter] = IContainer()
                for subSubE in subE:
                    FindEnd(subSubE)
                for i in range(len(inst)):
                    print inst[i]
                    print inst[i].dicList 

                counter += 1

When I run this

for i in range(len(inst)):
    print inst[i]
    print inst[i].dicList 

all the inst are replaced with the final loop's address and data....I havn't a clue what's going wrong.

Upvotes: 0

Views: 271

Answers (2)

Mike Lewis
Mike Lewis

Reputation: 64147

In your case, dicList is a class attribute, in which you want an instance attribute.

Class attributes only have one object to refer to(which is exactly the reason why you are getting those results) whereas instance attributes are created on instantiation, so each instance refers to their own dicList.

So you want to use instance attributes, in which you can achieve by creating said attribute in the constructor.

class IContainer:
    def __init__(self):
        self.dicList = {}

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798726

dicList is a class attribute.

class IContainer:
    def __init__(self):
        self.dicList = {}

Upvotes: 1

Related Questions