亚洲区国产区激情区无码区,国产成人mv视频在线观看,国产A毛片AAAAAA,亚洲精品国产首次亮相在线

Python 基礎(chǔ)教程

Python 流程控制

Python 函數(shù)

Python 數(shù)據(jù)類型

Python 文件操作

Python 對象和類

Python 日期和時間

Python 高級知識

Python 參考手冊

Python dict() 使用方法及示例

Python 內(nèi)置函數(shù)

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)。

示例1:僅使用關(guān)鍵字參數(shù)創(chuàng)建字典

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:使用可迭代創(chuàng)建字典

# 不傳遞關(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}

示例3:使用映射創(chuàng)建字典

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}

推薦閱讀: Python詞典以及如何使用它們 Python 內(nèi)置函數(shù)