【问题标题】:Python: Unexpected behaviour with dict and a colon. ( my_dict['key']: None ) what does the colon ( : ) do? [duplicate]Python:dict 和冒号的意外行为。 ( my_dict['key']: None ) 冒号 ( : ) 有什么作用? [复制]
【发布时间】:2020-02-15 09:33:18
【问题描述】:

我在 python 中遇到了一些与 dicts 相关的意外行为。
这可能是因为注释,但我不确定。
请看下面的sn-p:

>>> d = {}  # lets create a dictionary and add something to it.
>>> d['a'] = 'a'
>>> d
{'a': 'a'}
>>> d['a']
'a'
>>> # ok all well and good, we know how dicts work, right ?
...
>>> d['z']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'z'
>>>
>>> # yea no key 'z' was inserted. Lets add a colon (:) in the mix 
...
>>> d['z']: d
>>>
>>> # nothing happend! weird...
...
>>> d['z']: d['z']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'z'

>>> # again 'z' was not added to the dict, but what did the colon ???
...
>>> d['z']: d['z']: None
  File "<stdin>", line 1
    d['z']: d['z']: None
                  ^
SyntaxError: invalid syntax
>>>
>>> # NOW the colon gives an SyntaxError !?!
>>> # Lets try to directly use a colon after the dict
...
>>> {'a': 'a'}: ()
  File "<stdin>", line 1
SyntaxError: illegal target for annotation
>>>
>>> # so annotation huh ?
>>> # is it possible to annotate on the fly ?
...
>>> def func(x): return x
... 
>>> d = {'f': func}  # overwrite previous dict 
>>> d['f']: callable
>>> d['f'].__annotations__
{}
>>> # doesn't look like it was taken over
... # lets check if d['f'] returns the callable function: func
...
>>>
>>> def func(x: str) -> callable: return x
... 
>>> d = {'f': func}
>>> d['f'].__annotations__  # lets check for annotations !!
{'x': <class 'str'>, 'return': <built-in function callable>}
>>>
>>> # I'm confused, what does the colon do?
...
>>>

我很好奇为什么 dict 语法并不总是对给定的冒号 (:) 做出反应。
注释似乎也不是这样(或者我的结论是错误的)

那么亲爱的读者们,在上面描述的上下文中使用冒号的目的是什么?

【问题讨论】:

    标签: python python-3.x dictionary syntax colon


    【解决方案1】:

    冒号用于分隔键和值,但只有在括号中才有效。

    如文件所说

    在大括号内放置一个逗号分隔的键:值对列表 将初始键:值对添加到字典中;这也是方法 字典写在输出上

    https://docs.python.org/3/tutorial/datastructures.html

    【讨论】:

      【解决方案2】:

      经过长时间的深思熟虑,我得出结论,字典中的对象也可以是可迭代的。
      这意味着方括号后允许使用冒号。

      >>> d = {'a': 'abcd'}
      >>> for letter in d['a']: None # <- see here, look at the placement of the colon
      ...
      

      【讨论】:

      • 这只是for 语句的单行形式。您注意到的作为变量注解的初始构造允许在名称后面添加可选注解(例如类型提示,但任何表达式都是有效的)。 d[z]: d 中的冒号与在 dict 显示中使用冒号无关。
      猜你喜欢
      • 2019-09-14
      • 2012-09-25
      • 1970-01-01
      • 2021-12-22
      • 2018-11-21
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 2013-11-22
      相关资源
      最近更新 更多