2011-04-07 56 views
2

這是我的代碼:如何循環的字典在{}使用python

a = {0:'000000',1:'11111',3:'333333',4:'444444'} 

b = {i:j+'www' for i,j in a.items()} 
print b 

,並顯示錯誤:

File "g.py", line 7 
    b = {i:j+'www' for i,j in a.items()} 
        ^
SyntaxError: invalid syntax 

我如何糾正呢?

回答

3
{i:j+'www' for i,j in a.items()} 

Dictionary Comprehension在Python 3

工作正常,你可以在這裏看到:http://ideone.com/tbXLA(注意,我打電話打印爲在Python 3的功能)。

如果你有< Python 3,那麼它會給你這個錯誤。

要做這種類型的概念,你必須做列表/生成器表達式,它創建一個鍵,值的元組。一旦發生這種情況,你可以調用接受元組列表的dict()。

dict((i,j+'www') for i,j in a.items()) 
+0

但是在Python 3,你必須使用打印的功能:打印(B) – 2011-04-07 03:47:28

+0

是的,絕對 – 2011-04-07 03:51:16

+2

[Python 2.7版(http://docs.python.org/dev /whatsnew/2.7.html)也有詞典解釋。 – intuited 2011-04-07 04:56:01

3
b = {i:j+'www' for i,j in a.items()} #will work in python3+ 

上面的是一個dict理解(注意括號中)。它們已經在Python3中引入。
我想你使用Python2.x只支持list理解。

b = dict((i:j+'www') for i,j in a.items()) #will work in python2.4+ 
      <-----generator exression-------> 

More on generators.