11

Python は、dict に対して受け入れるキーの種類に矛盾があるようです。または、別の言い方をすれば、辞書を定義する 1 つの方法では特定の種類のキーを許可しますが、他の方法では許可しません。

>>> 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")ですか?

私は興味がある...

4

4 に答える 4

18

これはdict問題ではありませんが、Python 構文のアーティファクトです。キーワード引数は有効な識別子である必要があり、そうでは1あり2ません。

Python 識別子規則に従って文字列以外のものをキーとして使用する場合は、{}構文を使用します。コンストラクターのキーワード引数の構文は、いくつかの特別な場合に便利なように用意されています。

于 2012-04-30T21:10:44.540 に答える
9

dictは関数呼び出しであり、関数キーワードは識別子でなければなりません。

于 2012-04-30T21:11:05.433 に答える
2

他の回答が述べているように、dictは関数呼び出しです。3 つの構文形式があります。

フォーム:

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

キー (またはnameこの場合は使用) は有効な Python識別子である必要があり、int は無効です。

制限は関数だけではありません。次の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

ただし、使用できる構文形式は他に 2 つあります。

がある:

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はマッピングであり、これがそれらの 1 つを 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}
于 2016-10-04T16:34:51.507 に答える