Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing dictionary keys using dot(.) [duplicate]

Tags:

python

I can not access the dictionary keys with dot(.) but when I define a class that inherits from dict, I can access its keys using dot(.). Can anybody explain it?

So, when I run this code:

d = {'first_key':1, 'second_key':2}
d.first_key

I get this error:

'dict' object has no attribute 'first_key'

but when I run this:

class DotDict(dict):
    pass
d = DotDict()
d.first_key = 1
d.second_key = 2
print(d.first_key)
print(d.second_key)

I get this:

1
2
like image 340
pythinker Avatar asked Jan 28 '23 01:01

pythinker


2 Answers

By applying your example

class DotDict(dict):
    pass

d = DotDict()
d.first_key = 1
d.second_key = 2
print(d.first_key)
print(d.second_key)

you set instance parameters first_key and second_key to your DotDict class but not to the dictionary itself. You can see this, if you just put your dictionary content to the screen:

In [5]: d
Out[5]: {}

So, it is just an empty dict. You may access dictionaries the common way:

In [1]: d={}

In [2]: d['first'] = 'foo'

In [3]: d['second'] = 'bar'

In [4]: d
Out[4]: {'first': 'foo', 'second': 'bar'}
like image 110
ferdy Avatar answered Jan 30 '23 14:01

ferdy


in the first case, you are creating keys and values belonging to a dictionary object. while in the second, you are creating attributes of a class which has nothing to do with the dictionary parent class you inherited.

like image 30
lelouchkako Avatar answered Jan 30 '23 15:01

lelouchkako