如何使用python在{}中循环一个dict

时间:2011-04-07 03:38:59

标签: python loops dictionary

这是我的代码:

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

我该如何纠正?

2 个答案:

答案 0 :(得分:4)

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

Dictionary Comprehension在Python 3中运行良好。

正如您在此处所见:http://ideone.com/tbXLA(注意,我在Python 3中将print称为函数)。

如果你有< Python 3,那么它会给你这个错误。

要做这种类型的概念,你必须做list / generator表达式,它创建一个key,value的元组。一旦发生这种情况,你可以调用dict()接受一个元组列表。

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

答案 1 :(得分:3)

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

以上是dict理解(注意花括号)。它们已在Python3中引入 我猜你使用的是仅支持list理解的Python2.x.

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

More on generators.