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
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'}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With