1

I am creating a class and setting some properties. And I am referencing dictionary as a class object. But not able to access the second element of the object.

I tried to google the problem but it does not specify the cause of my problem.

data = {
'a': {
'vsdf': 'asfas',
'nfgn': 'aser',
'aser': 'rtydf'
},
'b': ['ndfg', 'ndf', 'safd']
}

My class looks something like this:
    def __init__(self, meta):
        self.meta = meta

and when i create the object of this class like this:

request = Request(data)

and try to print the request['b'] it shows the error "'Request' object is not subscriptable" 

Actual result should be like : ['', '', '']

but it shows: 'Request' object is not subscriptable

Prithvi Singh
  • 97
  • 1
  • 10

1 Answers1

1

With the code you have given, the data dictionary will be stored in the meta instance variable. You'll need to access it by first accessing that variable, i.e. request.meta['b'].

In order to get it to act the way you want, you'll need to loop through the dict passed in to __init__ and set each variable individually. Take a look at this answer for how to do that: Set attributes from dictionary in python

Rob Streeting
  • 1,675
  • 3
  • 16
  • 27
  • yeah i did and it worked but i didnt get the reason for that? – Prithvi Singh Aug 30 '19 at 12:35
  • Basically, python object attributes are not a dictionary like they are in something like perl (even though behind the scenes they are implemented as a dictionary). You can't set them wholesale in one operation. As far as I can find myself, self.meta has no special meaning in python, so you're just setting an attribute called "meta" on your object to a copy of the "data" dictionary you passed in. – Rob Streeting Aug 30 '19 at 12:41