开发者

how to loop a dict in a {} using python

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()}
                      ^
SyntaxEr开发者_StackOverflowror: invalid syntax

How can I correct this?


{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())


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

The above is a dict comprehension (note curly braces). They have been introduced in Python3.
I guess you are using Python2.x which supports only list comprehensions.

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

More on generators.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜