Python:使用带有整数键的 dict() 创建字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32544835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: create dictionary using dict() with integer keys?
提问by Sindyr
In Python, I see people creating dictionaries like this:
在 Python 中,我看到人们创建这样的字典:
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 integerkeys using the dict() function/constructor?
这工作正常,但我的主要问题是:有没有办法使用 dict() 函数/构造函数设置整数键?
采纳答案by BrenBarn
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."
有几种不同的方法可以制作 dict。如文档所述,“提供关键字参数 [...] 仅适用于有效 Python 标识符的键。”
回答by Malavan Satkunarajah
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.
在本示例中提供关键字参数仅适用于作为有效 Python 标识符的键。否则,可以使用任何有效的密钥。
回答by Aivar Paalberg
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}