Preface: I've spent many HOURS trying to read similar posts like this one and try lots of different things, but for the life of me, I can't understand what I'm doing wrong, or why this doesn't work. Can someone please give me an ELI5 answer as to either what I'm doing wrong, or why this doesn't work the way I'm expecting?
class User:
def __init__(self, first, last, age):
self.firstname = first
self.lastname = last
self.age = age
dict = {
'User1': {'id': 'id001', 'firstname': 'User', 'lastname': 'One', 'age': 11},
'User2': {'id': 'id002', 'firstname': 'User', 'lastname': 'Two', 'age': 22},
'User3': {'id': 'id003', 'firstname': 'User', 'lastname': 'Three', 'age': 33}
}
for user in dict:
u = dict[user]
user = User(u['firstname'], u['lastname'], u['age'])
try:
print(User1.lastname)
except Exception as e:
print(e)
finally:
print(user.lastname)
Which returns:
name 'User1' is not defined
Three
Clearly user is getting instantiated three times with the data from dict, with User3's data being the last of it.
If I do a:
for user in dict:
print(user)
it prints out:
User1
User2
User3
So my expectation would be that the for loop would run, and then I'd be able to call User1.firstname, User2.lastname, or User3.age, and it'd give me the same data that's in dict (User, Two, 33, respectively), but that's clearly not the case.
Help?
User1. You have a key in a dictionary with that name, and can access that user's variables withprint(dict['User1']['lastname']. There is a not a good way in python to convert a dictionary key directly to a variable/class name withouteval(don't useeval), meaning there is not a good way to get a variable calledUser1unless you manually sayUser1 = User(...). If you want your users in classes, you can make a dictionary or list of users as g.d.d.c. has done.User3. If you want to do something special with a certain user, you can add aself.useridfield to yourUserclass, and then when you're looping through your list with offor user in usersyou can checkif user.userid == User3.