【问题标题】:when can I use dot notation to access a dictionary in Python什么时候可以使用点符号来访问 Python 中的字典
【发布时间】:2020-02-20 10:50:52
【问题描述】:

我正在“gym”环境的上下文中修改某人的代码,并发现使用点符号来访问字典。 下面的 sn-p 表明,gym 中的字典可以使用该符号,但是当我复制它时会引发错误。

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)

这提供了以下输出:

{'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'

我正在使用 Python 3。有人可以解释一下吗? 谢谢

【问题讨论】:

  • dict 值不能使用点表示法访问。 config 可能不是 dict - 使用 type(config) 找出它是什么。
  • 我猜你已经习惯了 javascript 的语法和语义?
  • 你是正确的配置是一个 谢谢你。

标签: python dictionary notation


【解决方案1】:

与 JavaScript 对象不同,Python 字典本身不支持点表示法。

尝试DotsiAddict 或类似的库。下面是 Dotsi 的快速 sn-p:

>>> 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'
>>> 

披露:我是 Dotsi 的作者。

【讨论】:

    【解决方案2】:

    在python中你不能用dict.key访问字典值,你需要使用dict[key]

    例子:

    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'
    

    如果你真的想使用点符号,你可以使用一个类(顺便说一下,你的config 可能是一个类实例):

    class MyClass():
        def __init__(self):
            self.foo = "bar"
    
    a = MyClass()
    print(a.foo)
    # bar
    

    【讨论】:

    • 我通常使用 dict[key] 但我正在更改的代码似乎成功地使用了点符号,我想了解如何。
    • cf 在我的回答中,关于类的部分:您可以将点符号与类实例一起使用
    猜你喜欢
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 2016-02-21
    • 2019-07-31
    • 2015-11-25
    相关资源
    最近更新 更多