开发者

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

开发者 https://www.devze.com 2023-02-18 10:38 出处:网络
this is my code : print dict(range(3)开发者_如何学C,range(3)) but it show error : Traceback (most recent call last):

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

精彩评论

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