【问题标题】:If dict(a=1) is accepted then why not dict(1=1)?如果 dict(a=1) 被接受,那么为什么不接受 dict(1=1)?
【发布时间】:2020-08-18 21:25:10
【问题描述】:

我已经开始学习 Python 3 并遇到了字典主题。

例如,可以使用dict关键字创建字典,例如:

>>> exp=dict(a=2,b=5,c=8)
>>> exp
{'a': 2, 'b': 5, 'c': 8}

但是,当我尝试使用整数作为键时,它会返回错误。

>>> exp=dict(1=2, 2=3)
File "<stdin>", line 1
SyntaxError: keyword can't be an expression

然后我尝试只使用花括号,效果很好

>>> exp = {1:2,2:3}
>>> exp
{1: 2, 2: 3}

我可以知道为什么会这样吗?

【问题讨论】:

标签: python dictionary


【解决方案1】:

您正在传递 dict 构造函数关键字参数。 keyword argument 必须是 identifier 后跟等号,然后是 expression。但是,您提供的是整数而不是标识符。同时,dict 文字(用大括号括起来)没有这个限制。

【讨论】:

    【解决方案2】:

    12 不是有效的关键字参数。 Here 是来源。

    您可以使用exp = {1:2,2:3}(您自己已经知道了),也可以使用exp=dict([(1, 2), (2, 3)])

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多