keywords参数必须是有效的标识符,而数字不是。

官方文档里的dict部分也写了,直接在索引里搜「dict」,选择(built-in class),有:

&>&>&> a = dict(one=1, two=2, three=3)
&>&>&> b = {one: 1, two: 2, three: 3}
&>&>&> c = dict(zip([one, two, three], [1, 2, 3]))
&>&>&> d = dict([(two, 2), (one, 1), (three, 3)])
&>&>&> e = dict({three: 3, one: 1, two: 2})
&>&>&> f = dict({one: 1, three: 3}, two=2)
&>&>&> a == b == c == d == e == f
True

Providing keyword arguments as in the first example only works for keys that are valid Python identifiers.


键只要是不可变的就行,数字不数字不是重点。数字做键天然支持


据我所知,Python 字典的键可以使用的数据类型除了字元串以外,还有数字、元组等。

以下例子创建一个键为数字的简单的字典:

当然也可以给这个字典添加其他数据类型的键值对:

另外,创建空白字典时,使用 a = {} 也是可以的。

----- 2021-2-19 分割线 -----

有朋友回答此题说数字不能作为键,但官方文档是这样说的:


需求确定:python利用dict函数创建键为数字的键值对

dict()函数用法:

dict 语法

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

参数说明

  • **kwargs -- 关键字
  • mapping -- 元素的容器。
  • iterable -- 可迭代对象。

dict() # 创建空字典
dict(a=a, b=b, t=t) # 传入关键字
dict(zip([one, two, three], [1, 2, 3])) # 映射函数方式来构造字典
dict([(one, 1), (two, 2), (three, 3)]) # 可迭代对象方式来构造字典
dict([(1, 1), (two, 2), (three, 3)])

总结:dict()函数能够创建键为数字的键值对。

注:python基础,可以参考如下书籍

电子书Python 数据分析基础作者 Clinton W. Brownley会员专享¥ 34.99去查看?

电子书数据分析从入门到进阶作者 陈红波 等会员专享¥ 51.94去查看?


dict(1:10)就没问题啊,是数字键。


书上写可以通过dict(key=value)的形式创建给定键值对的字典,但是我在创建时如果键是数字的时候,比如a=dict(1 = 10)就会显示错误,而用a={1:10}则没有问题。所以如果我想用dict()函数创建键为数字的键值对应该怎么做呢?还是说dict()函数不能创建键为数字的键值对?键为元组如a=dic((1,2,3)=123)也不行。


推荐阅读:
相关文章