2012-04-30 35 views
10

Python似乎在它將接受的字典中使用哪種密鑰時會出現不一致。或者,換一種方式,它允許某些類型的密鑰定義類型的字典的一種方式,但不是在別人:python SyntaxError with dict(1 = ...),但{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")

我很好奇......

回答

17

這不是一個dict問題,但Python語法的神器:關鍵字參數必須是有效的標識符,並12都沒有。

當您想要將任何非Python字符串規則以外的字符串用作關鍵字時,請使用{}語法。在一些特殊情況下,構造函數關鍵字參數的語法就是爲了方便。

9

dict是一個函數調用,函數關鍵字必須是標識符。

1

如果你讀了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 
1

至於其他答案已經指出,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} 

雖然這可能看起來不多(從字面的字典的字典)沒有記住,Counterdefaultdict的映射,這是你如何將這些隱蔽的字典之一:

>>> 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} 
相關問題