python中dict()函数的三种参数构造字典用法

python中的dict()函数

dict()函数是python的内置函数,一般情况下用来构造python的dict字典类型的数据,返回值为dict。


dict()函数的三种参数类型

dict()函数在不传递参数的情况下,可以返回一个空的字典,如果传递参数的话,可以传递三种类型,其源码如下:

  • dict(mapping) -> new dictionary initialized from a mapping object's:字典类型的参数为映射类型数据,比如dict字典类型;
  • dict(iterable) -> new dictionary initialized as if via:参数为可迭代对象,一般为二元的可迭代对象,具体可看下方实例;
  • dict(**kwargs) -> new dictionary initialized with the name=value pairs:关键词参数;

dict()函数实例代码

>>> dict() #不传递参数,生成空dict
{}
>>> dict({'a':1,'b':2}) #传递的是映射类型的数据,比如dict,生成dict
{'a': 1, 'b': 2}
>>> dict([['c',5],['d',6]]) #可迭代对象作为dict函数的参数一般情况下是二元的
{'c': 5, 'd': 6}
>>> dict((('e',8),)) #二元的元组,当二元的元组只有一个元素时,注意后面的逗号
{'e': 8}
>>> dict(g=11,h=12) #关键词参数
{'g': 11, 'h': 12}
>>> dict([1,2]) #一元的列表作为参数,会抛出TypeError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot convert dictionary update sequence element #0 to a sequence
>>> dict(('f',9)) #一元的元组亦是如此
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> dict('g'=11,'h'=12) #关键词作为dict的参数时,注意key的语法
  File "<stdin>", line 1
SyntaxError: keyword can't be an expression
>>> dict(zip(('i','j','k'),(15,16,17))) #还可以通过zip函数来创造映射
{'i': 15, 'j': 16, 'k': 17}

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.