📅  最后修改于: 2020-09-20 03:57:36             🧑  作者: Mango
dict()
构造函数的不同形式是:
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
注意: **kwarg
允许您接受任意数量的关键字参数。
关键字参数是一个以标识符(例如name=
)开头的参数。因此,将形式为kwarg=value
的关键字参数传递给dict()
构造函数以创建字典。
dict()
不返回任何值(返回None
)。
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}
empty = {}
# keyword argument is not passed
numbers1 = dict([('x', 5), ('y', -5)])
print('numbers1 =',numbers1)
# keyword argument is also passed
numbers2 = dict([('x', 5), ('y', -5)], z=8)
print('numbers2 =',numbers2)
# zip() creates an iterable in Python 3
numbers3 = dict(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}
numbers1 = dict({'x': 4, 'y': 5})
print('numbers1 =',numbers1)
# you don't need to use dict() in above code
numbers2 = {'x': 4, 'y': 5}
print('numbers2 =',numbers2)
# keyword argument is also passed
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词典以及如何使用它们。