dict()構(gòu)造函數(shù)在Python中創(chuàng)建一個字典。
dict()構(gòu)造函數(shù)的有多種形式,分別是:
class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg)
注意:**kwarg允許您接受任意數(shù)量的關(guān)鍵字參數(shù)。
關(guān)鍵字參數(shù)是一個以標(biāo)識符(例如name=)開頭的參數(shù)。因此,表單的關(guān)鍵字參數(shù)將kwarg=value傳遞給dict()構(gòu)造函數(shù)以創(chuàng)建字典。
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}
<class 'dict'>
empty = {}
<class 'dict'># 不傳遞關(guān)鍵字參數(shù)
numbers1 = dict([('x', 5), ('y', -5)])
print('numbers1 =',numbers1)
# 關(guān)鍵字參數(shù)也被傳遞
numbers2 = dict([('x', 5), ('y', -5)], z=8)
print('numbers2 =',numbers2)
# zip() 在Python 3中創(chuàng)建一個可迭代的對象
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)
# 您不需要在上述代碼中使用dict()
numbers2 = {'x': 4, 'y': 5}
print('numbers2 =',numbers2)
#關(guān)鍵字參數(shù)也被傳遞
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}