Python: 使用带整数键的 dict() 创建字典?

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

在 Python 中,我看到人们创建这样的词典:

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

如果我的密钥是整数怎么办?当我尝试这个时:

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

我收到一个错误。我当然可以这样做:

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

效果很好,但我的主要问题是:有没有办法使用 dict() function/constructor?

设置 integer

是的,但不是那个版本的构造函数。你可以这样做:

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

口述有几种不同的方法。如documented、"providing keyword arguments [...] only works for keys that are valid Python identifiers."

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

在此示例中提供关键字参数仅适用于作为有效 Python 标识符的键。否则,可以使用任何有效密钥。

还有这些'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}