when can I use dot notation to access a dictionary in Python
I am modifying somebody's code in the context of the 'gym'' environment and came across the use of the dot notation to access a dictionary. the following snippet shows that the dictionary in gym can use the notation but when I duplicate it it throws an error.
import gym
env = gym.Env
env = make('connectx', debug=True)
config = env.configuration
print(config)
print(config.timeout)
dct = {'timeout': 5, 'columns': 7, 'rows': 6, 'inarow': 4, 'steps': 1000}
print(dct.timeout)
this provides the following output:
{'timeout': 5, 'columns': 7, 'rows': 6, 'inarow': 4, 'steps': 1000}
5
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-45-674d59d34c55> in <module>
6 print(config.timeout)
7 dct = {'timeout': 5, 'columns': 7, 'rows': 6, 'inarow': 4, 'steps': 1000}
----> 8 print(dct.timeout)
AttributeError: 'dict' object has no attribute 'timeout'
I am using Python 3. Can somebody explain please? Thanks
Solution 1:
Unlike JavaScript objects, Python dicts don't natively support dot notation.
Try Dotsi, Addict or a similar library. Here's a quick snippet of Dotsi in action:
>>> import dotsi
>>>
>>> d = dotsi.Dict({"foo": {"bar": "baz"}}) # Basic
>>> d.foo.bar
'baz'
>>> d.users = [{"id": 0, "name": "Alice"}] # In list
>>> d.users[0].name
'Alice'
>>>
Disclosure: I'm Dotsi's author.
Solution 2:
In python you cannot access a dictionnary value with dict.key
, you need to use dict[key]
Example :
d = {"foo": 2}
print(d["foo"])
# 2
key = foo
print(d[key])
# 2
print(d.foo)
# AttributeError: 'dict' object has no attribute 'foo'
print(d.key)
# AttributeError: 'dict' object has no attribute 'key'
If you really want to use the dot notation, you can use a class (your config
is probably a class instance by the way):
class MyClass():
def __init__(self):
self.foo = "bar"
a = MyClass()
print(a.foo)
# bar