Home > Back-end >  How to Construct Method and Attributes using Dictionaries in Python
How to Construct Method and Attributes using Dictionaries in Python

Time:11-28

class print_values:
    def __init__(self,username,user_email,displayname):
        self.name= username
        self.email=user_email
        self.DisplayName=displayname
    def printing_content(self):
        print(f"UserName: {self.name}\n"
              f"UserEmail: {self.email}\n"
              f"UserDisplayName:{self.DisplayName}\n")

user_one={'username':'userone',
            'useremail':'[email protected]',
            'displayname':'User One'}

user_two={'username':'usertwo',
            'useremail':'[email protected]',
            'displayname':'User Two'}

user_three={'username':'userthree',
            'useremail':'[email protected]',
            'displayname':'User Three'}

users_list=['user_one','user_two','user_three']


obj_name=print_values(user_one['username'],user_one['useremail'],user_one['displayname'])

obj_name.printing_content()

It's working fine, as am getting output as below

UserName: userone
UserEmail: [email protected]
UserDisplayName:User One

Here am only using user_one dict, i want to do the same for multiple dict.

I have tried adding the dict names in list and try to loop through them, like below

for item in user_list:
    obj_name=print_values(item['username'],item['useremail'],item['displayname'])
    obj_name.printing_content()

But am getting below error

obj_name=print_values(item['username'],item['useremail'],item['displayname'])
TypeError: string indices must be integers

Any one do let me know what am i missing or anyother idea to get this done.

Thanks in advance!

CodePudding user response:

This is because in users_list=['user_one', 'user_two', 'user_three'] you enter the variable name as a string.

class print_values:
    def __init__(self,username,user_email,displayname):
        self.name= username
        self.email=user_email
        self.DisplayName=displayname
    def printing_content(self):
        print(f"UserName: {self.name}\n"
              f"UserEmail: {self.email}\n"
              f"UserDisplayName:{self.DisplayName}\n")

user_one={'username':'userone',
            'useremail':'[email protected]',
            'displayname':'User One'}

user_two={'username':'usertwo',
            'useremail':'[email protected]',
            'displayname':'User Two'}

user_three={'username':'userthree',
            'useremail':'[email protected]',
            'displayname':'User Three'}

users_list=[user_one,user_two,user_three] # edited


obj_name=print_values(user_one['username'],user_one['useremail'],user_one['displayname'])

obj_name.printing_content()


for item in users_list:
    obj_name=print_values(item['username'],item['useremail'],item['displayname'])
    obj_name.printing_content()

Explanation

Your users_list=['user_one', 'user_two', 'user_three'] is a string containing the variable names as the string. When you loop on user_list

for item in user_list:

Here item is not the user_one, or user_two as a variable but these are as the string means 'user_one', or 'user_two', so when you try to get values like item['username'], here you got the error because the item is not a dictionary or json or ..., but it is a string here, you can get the only provide an integer inside these brackets [], like 1, 2, 3, 4,..., ∞.

I hope you understand well. Thanks.


Don't make a dictionary for every user.

Use this code

class Users:

    def __init__(self) -> None:
        self.userList = []

    def addUser(self, user):
        self.userList.append(user)




class User:

    def __init__(self, username, email, name) -> None:
        self.username = username
        self.email = email
        self.name = name

    def __str__(self) -> str:
        return f"Username = {self.username}\nEmail = {self.email}\nName = {self.name}\n"
    

users = Users()


users.addUser(User("username1", "email1", "name1"))
users.addUser(User("username2", "email2", "name2"))



# First way of printing
for user in users.userList:
    print(user)  # Printing user directly prints the formatted output
                 # Because I have changed the magic `__str__` method in user class
                 # You can return anything('string data type only') in __str__ it will print when you print the class object.
# Second way of printing.

for user in users.userList:
    print("Username = "   user.username)
    print("Email = "   user.email)
    print("Name = "   user.name)
    print() # for adding one extra line

  • Related