2011-04-07 63 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.