Python: create dictionary using dict() with integer keys?

北城以北 提交于 2021-01-20 16:16:08

问题


In Python, I see people creating dictionaries like this:

d = dict( one = 1, two = 2, three = 3 )

What if my keys are integers? When I try this:

d = dict (1 = 1, 2 = 2, 3 = 3 )

I get an error. Of course I could do this:

d = { 1:1, 2:2, 3:3 }

which works fine, but my main question is this: is there a way to set integer keys using the dict() function/constructor?


回答1:


Yes, but not with that version of the constructor. You can do this:

>>> dict([(1, 2), (3, 4)])
{1: 2, 3: 4}

There are several different ways to make a dict. As documented, "providing keyword arguments [...] only works for keys that are valid Python identifiers."




回答2:


There are also these 'ways':

>>> dict.fromkeys(range(1, 4))
{1: None, 2: None, 3: None}
>>> dict(zip(range(1, 4), range(1, 4)))
{1: 1, 2: 2, 3: 3}



回答3:


a = dict(one=1, two=2, three=3)

Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.



来源:https://stackoverflow.com/questions/32544835/python-create-dictionary-using-dict-with-integer-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!