Home > Net >  How can I access the keys and values of the dictionary that is created by calling constructor __init
How can I access the keys and values of the dictionary that is created by calling constructor __init

Time:02-08

I have created a class where I've passed an argument dictionary in the constructor. Now I need to make a function inside a class where I could access the information of that created dictionary and print users information. My attempt in doing so generates an error 'dict' object is not callabe.

class User:
    def __init__(self,first_name,last_name,**info):
        info['first_name']=first_name
        info['last_name']=last_name
        self.items=info
    
        
    def info_user(self):
            print(self.items)
            
    def users_information(self):
        print('Users Information:\n')
        for key, values in self.items():
            print(key,":",values)
    

user_0=User('Sarthak','Banset',address='Kathmandu',sex='Male',qualification='undergrad')
user_0.info_user()
user_0.users_information()

CodePudding user response:

The issue is that you have made the confusing choice to call the dictionary attribute "items". With that said, here's a fix to your users_information function.

def users_information(self):
    print('Users Information:\n')
    for key, values in self.items.items():
        print(key,":",values)

CodePudding user response:

The problem is that you named your dict items, while you really want the .items() method of it

for key, value in self.items.items():
    ...

CodePudding user response:

To solve your problem just replace

for key, values in self.items():

with

for key, values in self.items.items():

However, I wouldn't do that if I were you. I would rename some variables first for avoiding confusion, and I wouldn't store the same objects received as arguments. I would make a copy of them. Here is a short refactor

class User:
    def __init__(self,first_name,last_name,**info):
        self.properties = dict()
        self.properties.update(info)
        self.properties['first_name'] = first_name
        self.properties['last_name'] = last_name
    
    def info_user(self):
        print(self.properties)
            
    def users_information(self):
        print('Users Information:\n')
        for key, values in self.properties.items():
            print(key,":",values)
    

user_0=User('Sarthak','Banset',address='Kathmandu',sex='Male',qualification='undergrad')
user_0.info_user()
user_0.users_information()

CodePudding user response:

Please try with below method:

 def users_information(self):
        print('Users Information:\n')
        for key in self.items:
          print(key, ':', self.items[key])
  •  Tags:  
  • Related