跳到主要内容

Python dict() 函数

dict() 构造函数的不同形式是:

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

注意: **kwarg 允许您接受任意数量的关键字参数。

关键字参数是在标识符(例如 name=)之前的参数。因此,形式为 kwarg=value 的关键字参数被传递给 dict() 构造函数以创建字典。

dict() 不返回任何值(返回 None)。

示例 1:仅使用关键字参数创建字典

numbers = dict(x=5, y=0)
print('numbers =', numbers)
print(type(numbers))

empty = dict()
print('empty =', empty)
print(type(empty))

输出

numbers = {'y': 0, 'x': 5}
<class 'dict'>
empty = {}
<class 'dict'>

示例 2:使用可迭代对象创建字典

# 未传递关键字参数
numbers1 = dict([('x', 5), ('y', -5)])
print('numbers1 =',numbers1)

# 也传递了关键字参数
numbers2 = dict([('x', 5), ('y', -5)], z=8)
print('numbers2 =',numbers2)

# zip() 在 Python 3 中创建可迭代对象
numbers3 = dict(zip(['x', 'y', 'z'], [1, 2, 3]))
print('numbers3 =',numbers3)

输出

numbers1 = {'y': -5, 'x': 5}
numbers2 = {'z': 8, 'y': -5, 'x': 5}
numbers3 = {'z': 3, 'y': 2, 'x': 1}

示例 3:使用映射创建字典

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)

输出

numbers1 = {'x': 4, 'y': 5}
numbers2 = {'x': 4, 'y': 5}
numbers3 = {'x': 4, 'z': 8, 'y': 5}

推荐阅读: Python 字典及其使用方法