【问题标题】:python SyntaxError with dict(1=...), but {1:...} works带有dict(1 = ...)的python SyntaxError,但{1:...}有效
【发布时间】:2012-05-10 13:28:18
【问题描述】:

Python 似乎在接受 dicts 的键类型方面存在不一致。或者,换一种说法,它允许某些类型的键以一种方式定义 dicts,但不允许使用其他方式:

>>> d = {1:"one",2:2}
>>> d[1]
'one'
>>> e = dict(1="one",2=2)
  File "<stdin>", line 1
  SyntaxError: keyword can't be an expression

{...} 表示法更基础,dict(...) 只是语法糖吗?是不是因为 Python 根本没有办法parse dict(1="one")

我很好奇……

【问题讨论】:

    标签: python dictionary notation


    【解决方案1】:

    这不是 dict 的问题,而是 Python 语法的产物:关键字参数必须是有效的标识符,而 12 不是。

    如果您想使用任何不是遵循 Python 标识符规则的字符串作为键,请使用 {} 语法。在某些特殊情况下,constructor 关键字参数语法只是为了方便。

    【讨论】:

      【解决方案2】:

      dict是函数调用,函数关键字必须是标识符。

      【讨论】:

        【解决方案3】:

        正如其他答案所述,dict 是一个函数调用。它具有三种句法形式。

        形式:

        dict(**kwargs) -> new dictionary initialized with the name=value pairs
           in the keyword argument list.  For example:  dict(one=1, two=2)
        

        键(或本例中使用的 name)必须是有效的 Python identifiers,并且整数无效。

        限制不只是dict这个函数你可以这样演示:

        >>> def f(**kw): pass
        ... 
        >>> f(one=1)    # this is OK
        >>> f(1=one)    # this is not
          File "<stdin>", line 1
        SyntaxError: keyword can't be an expression
        

        但是,您可以使用其他两种句法形式。

        有:

        dict(iterable) -> new dictionary initialized as if via:
               d = {}
               for k, v in iterable:
                   d[k] = v
        

        例子:

        >>> dict([(1,'one'),(2,2)])
        {1: 'one', 2: 2}
        

        从映射中:

        dict(mapping) -> new dictionary initialized from a mapping object's
           (key, value) pairs
        

        例子:

        >>> dict({1:'one',2:2})
        {1: 'one', 2: 2}
        

        虽然这可能看起来不多(来自 dict 文字的 dict),但请记住 Counterdefaultdict 是映射,这就是您将其中一个转换为 dict 的方式:

        >>> from collections import Counter
        >>> Counter('aaaaabbbcdeffff')
        Counter({'a': 5, 'f': 4, 'b': 3, 'c': 1, 'e': 1, 'd': 1})
        >>> dict(Counter('aaaaabbbcdeffff'))
        {'a': 5, 'c': 1, 'b': 3, 'e': 1, 'd': 1, 'f': 4}
        

        【讨论】:

          【解决方案4】:

          如果您阅读documentation,您将了解到dict = {stringA = 1, stringB = 2} 表示法在键是简单字符串时有效:

          当键是简单的字符串时,有时更容易指定 使用关键字参数的对:

          >>>
          >>> dict(sape=4139, guido=4127, jack=4098)
          {'sape': 4139, 'jack': 4098, 'guido': 4127}
          

          由于整数(或其他数字)不是有效的关键字参数,dict = {1 = 2, 3 = 4} 将失败,因为如果您在用数字命名时将参数传递给它,则任何对函数的调用都会失败:

          >>> def test(**kwargs):
          ...     for arg in kwargs:
          ...         print arg, kwargs[arg]
          ... 
          >>> test(a=2,b=3)
          a 2
          b 3
          >>> test(1=2, 3=4)
            File "<stdin>", line 1
          SyntaxError: keyword can't be an expression
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-06-13
            • 1970-01-01
            • 1970-01-01
            • 2019-07-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多