开发者

best way to create a dict like {0:0,1:1,2:2} using python

this is my code :

print dict(range(3)开发者_如何学C,range(3))

but it show error :

Traceback (most recent call last):
  File "c.py", line 7, in <module>
    print dict(range(3),range(3))
TypeError: dict expected at most 1 arguments, got 2

what can i do ,

thanks


You could use a dictionary comprehension which works in Python 2.7 or newer:

{ i: i for i in range(3) }

Or for older versions of Python you can do this:

dict((i, i) for i in range(3))


This should work

 dict(zip(range(3),range(3)))


A longer but easy to understand way:

d={}
for x in range(3):
    d[x]=x

print d
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜