1

Let's say Bob enters his name, 'Bob Jones,' into a Tkinter text entry field. Later, I want to be able to access his name like this:

BobJones = {
'name':'Bob Jones',
'pet\'s name':'Fido'
}

How do I make it so I assign whatever Bob inputs as a new variable without having to manually write it in?

Thanks in advance.

8
  • keep your data out of your variable names Commented Apr 9, 2014 at 0:22
  • @roippi that doesn't really help Commented Apr 9, 2014 at 0:32
  • So you will have variables whose names aren't known when the program is written, and no other way of finding their names once they have been created? How could this possibly be a good idea? Commented Apr 9, 2014 at 0:34
  • 1
    You're looking for a dictionary. Commented Apr 9, 2014 at 0:35
  • @ScottHunter how do you make "new users" then? I'm pretty new to this :/ Commented Apr 9, 2014 at 0:36

1 Answer 1

1

To expand on the comments above, I think you'd want something more like this:

# Define the user class - what data do we store about users:

class User(object):
    def __init__(self, user_name, first_pet):
        self.user_name = user_name
        self.first_pet = first_pet

# Now gather the actual list of users

users = []
while someCondition:
    user_name, first_pet = getUserDetails()
    users.append(User(user_name, first_pet))

# Now we can use it

print "The first users name is:"
print users[0].user_name

So you're defining the class (think of it as a template) for the Users, then creating new User objects, one for each person, and storing them in the users list.

Sign up to request clarification or add additional context in comments.

3 Comments

wow, I can't believe I forgot about classes! thanks a lot, man
No problem. If you're after sometihng lighter-weight than this (and the data will never be changed 'immutable'), you could use Named Tuples instead of classes, e.g. stackoverflow.com/questions/2970608/…
No I definitely need to use classes. I'm storing ~50 data points per user.

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.