Python dict() 函数
目录
描述
语法
参数
返回值
实例
只使用关键字参数创建字典
使用可迭代对象创建字典
使用映射来创建字典
描述
用于创建一个字典
语法
class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg)
参数
- **kwargs -- 关键字
- mapping -- 元素的容器,映射类型(Mapping Types)是一种关联式的容器类型,它存储了对象与对象之间的映射关系
- iterable -- 可迭代对象
返回值
字典
实例
print( dict() ) # 创建空字典
print( dict(a='a', b='b', t='t') ) # 传入关键字
print( dict(zip(['one', 'two', 'three'], [1, 2, 3])) ) # 映射函数方式来构造字典
print( dict([('one', 1), ('two', 2), ('three', 3)]) ) # 可迭代对象方式来构造字典
只使用关键字参数创建字典
numbers = dict(x=5, y=0)
print('numbers =', numbers)
print(type(numbers))empty = dict()
print('empty =', empty)
print(type(empty))
使用可迭代对象创建字典
# 没有设置关键字参数
numbers1 = dict([('x', 5), ('y', -5)])
print('numbers1 =',numbers1)# 设置关键字参数
numbers2 = dict([('x', 5), ('y', -5)], z=8)
print('numbers2 =',numbers2)# zip() 创建可迭代对象
numbers3 = dict(dict(zip(['x', 'y', 'z'], [1, 2, 3])))
print('numbers3 =',numbers3)
使用映射来创建字典
numbers1 = dict({'x': 4, 'y': 5})
print('numbers1 =',numbers1)# 以下代码不需要使用 dict()
numbers2 = {'x': 4, 'y': 5}
print('numbers2 =',numbers2)# 关键字参数会被传递
numbers3 = dict({'x': 4, 'y': 5}, z=8)
print('numbers3 =',numbers3)
内容借鉴于菜鸟教程,感谢
我有一些个人的见解:dict()函数的核心是“可迭代的键值对”,关于映射函数zip()和可迭代对象这两种方式,我觉得就像 列表元组 和 元组列表,只不过列表元组需要映射一下才好形成键值对
Python dict() 函数 | 菜鸟教程https://www.runoob.com/python/python-func-dict.html