Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Construct Method and Attributes using Dictionaries in Python

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':'userone@gmail.com',
            'displayname':'User One'}

user_two={'username':'usertwo',
            'useremail':'usertwo@gmail.com',
            'displayname':'User Two'}

user_three={'username':'userthree',
            'useremail':'userthree@gmail.com',
            '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: userone@gmail.com
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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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':'userone@gmail.com',
            'displayname':'User One'}

user_two={'username':'usertwo',
            'useremail':'usertwo@gmail.com',
            'displayname':'User Two'}

user_three={'username':'userthree',
            'useremail':'userthree@gmail.com',
            '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)

# 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading