天天看點

Python标準庫:内置函數dict(iterable, **kwarg)

本函數是從可疊代對象來建立新字典。比方一個元組組成的清單,或者一個字典對象。

樣例:

#dict()
#以鍵對方式構造字典
d1 = dict(one = 1, two = 2, a = 3)
print(d1)

#以映射函數方式來構造字典
d2 = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
print(d2)

#可疊代對象方式來構造字典
d3 = dict([('one', 1), ('two', 2), ('three', 3)])
print(d3)

d4 = dict(d3)
print(d4)      

輸出結果例如以下:

{'a': 3, 'two': 2, 'one': 1}

{'two': 2, 'one': 1, 'three': 3}

繼續閱讀