第一種方式:使用{} firstDict = {"name": "wang yuan wai ", "age" : 25} 說明:{}為創建一個空的字典對象 第二種方式:使用fromkeys()方法 second_dict = dict.fromkeys(("name", "age")) #valu ...
第一種方式:使用{}
firstDict = {"name": "wang yuan wai ", "age" : 25}
說明:{}為創建一個空的字典對象
第二種方式:使用fromkeys()方法
second_dict = dict.fromkeys(("name", "age")) #value使用預設的None,也可以指定value值
說明:fromkeys()是dict類的一個staticmethod(靜態方法)
第三種方式:使用dict的構造方法,參數為關鍵字參數
thirdDict = dict(name = "yuan wai", age = 30) #利用dict的構造方法 傳入字典參數
第四種方式:使用dict的構造方法,參數為嵌套元組的list
tuple_list =[("name", "wang yuan wai"), ("age", 30)] my_dict = dict(tuple_list)
說明:傳入的list結構是有要求的,list的每個元素都是一個兩個元素的tuple
第五種方式:使用dict的構造方法,參數為zip()函數的返回值
fifthDict = dict(zip("abc",[1,2,3]))
第六種方式:使用dict的初始化方法,參數為字典對象
e = dict({'three': 3, 'one': 1, 'two': 2})
第七種方式:使用字典解析式
sixthDict = {char : char* 2 for char in "TEMP"}
創建字典的方式(官方文檔介紹)
以下示例返回的字典均等於 {“one”: 1, “two”: 2, “three”: 3}
>>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2}) >>> a == b == c == d == e True
第八種方式:使用字典的copy()方法(淺複製)創建一個新的字典對象
>>> hold_list=[1,2,3] >>> old_dict={"num":hold_list} >>> new_dict=old_dict.copy() >>> id(old_dict["num"]) 2141756678856 >>> id(new_dict["num"]) 2141756678856
淺複製:old_dict與new_dict持有的是同一個hold_list對象,你明白了嗎?註意看id值
第九種方式:使用copy模塊的deepcopy()函數(深複製)創建一個新的字典對象
>>> from copy import deepcopy >>> hold_list=[1,2] >>> old_dict={"num":hold_list} >>> new_dict=deepcopy(old_dict) >>> id(old_dict["num"]) 2141787030152 >>> id(new_dict["num"]) 2141787012040 # Python學習交流群 708525271
深複製:new_dict持有的也是一個新創建的host_list對象,你明白了嗎?註意看id值