Python:使用带整数键的dict()创建字典? [英] Python: create dictionary using dict() with integer keys?
本文介绍了Python:使用带整数键的dict()创建字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,我看到人们在创建像这样的字典:
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 }
这很好用,但是我的主要问题是:是否可以使用dict()函数/构造函数设置整数键?
which works fine, but my main question is this: is there a way to set integer keys using the dict() function/constructor?
推荐答案
是的,但不适用于该版本的构造函数.您可以这样做:
Yes, but not with that version of the constructor. You can do this:
>>> dict([(1, 2), (3, 4)])
{1: 2, 3: 4}
有几种不同的方法可以做出命令.正如已记录,提供关键字参数[... ]仅适用于有效的Python标识符的键."
There are several different ways to make a dict. As documented, "providing keyword arguments [...] only works for keys that are valid Python identifiers."
这篇关于Python:使用带整数键的dict()创建字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文