如何使用python在{}中循环一个字典(how to loop a dict in a {} using 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

我怎么能纠正这个?

This is my code :

a = {0:'000000',1:'11111',3:'333333',4:'444444'} b = {i:j+'www' for i,j in a.items()} print b

and it shows error :

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

How can I correct this?

最满意答案

{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()) {i:j+'www' for i,j in a.items()}

Dictionary Comprehension works fine in Python 3.

As you can see here: http://ideone.com/tbXLA (note, I am calling print as a function in Python 3).

If you have < Python 3, then it will give you this error.

To do this type of concept, you must do list/generator expression which creates a tuple of key, value. Once this happens, you can call dict() which accepts a list of tuples.

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

更多推荐