0

I'd like to create a dictonary: {int, Class} in a loop, however the class object is being overriden. I am pretty sure that this is a basic problem, but I am stuck

class Simple:
    simpleDic = {
        'name': {""},
        'age': {1}}

    def __init__(self, name, age):
        self.simpleDic['name'] = name
        self.simpleDic['age'] = age
    
    def __str__(self):
        return "{} {}\n".format(self.simpleDic['name'], self.simpleDic['age'])

def foo():
    myDict = {}
    for x in range(3):
        myDict[x] = Simple('Name' + str(x), x)
        print(('{}: {}\n'.format("Creating", myDict[x])))
    
    for key in myDict:
        print(('{}: {}\n'.format("Printing" + str(key), myDict[key])))


#### Main program here ####

foo()

The output is as follows:

enter image description here

1 Answer 1

1

You're problem is on the last print You're printing myDict[x] when you should print myDict[key]

x contains the last value from the first iteration, so you're practically printing the same key all over

Following your question in this comments:

class Simple:

    def __init__(self, name, age):
        self.simpleDic = {"name": name, "age": age}
    
    def __str__(self):
        return "{} {}\n".format(self.simpleDic['name'], self.simpleDic['age'])
    
    def __repr__(self):
        return "{} {}\n".format(self.simpleDic['name'], self.simpleDic['age'])    

def foo():
    myDict = {}
    for x in range(3):
        myDict[x] = Simple('Name' + str(x), x)
        print(('{}: {}\n'.format("Creating", myDict[x])))
        
    print(myDict)
Sign up to request clarification or add additional context in comments.

7 Comments

My goodness, what a stupid mistake. I am sorry about that.
Happens to the best of us :)
And what if i changed the code as in question now (replaced simple variable with a dictionary):
Then it would fail, as myDict belongs to the scope of the foo function, and you would get a NameError: name 'myDict' is not defined
You can return myDict in the foo function, and assign it to a variable on the global scope (before your loop)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.